angular - 下拉更改后组件参数不变
问题描述
我有以下基于下拉菜单的下拉代码。
<select [(ngModel)]="input-country">
<option *ngFor="let country of countries" [value]="country"> {{ country }}</option>
</select>
<select *ngIf="country" [(ngModel)]="input-city" (ngModelChange)="updateCity($event)>
<option *ngFor="let city of cities" [value]="city"> {{ city }} </option>
</select>
然后我根据选定的选项加载一个 div 并将国家和城市参数传递给这样的组件
<div *ngIf="city">
<app-render [country]="country" [city]="city"></app-render>
</div>
app.component.ts
export class AppComponent {
private map = new Map<string, string[]>([
['Poland', ['Warszawa', 'Krakow']],
['USA', ['New York', 'Austin']],
])
country: string;
city: string;
get countries(): string[] {
return Array.from(this.map.keys());
}
get cities(): string[] | undefined {
return this.map.get(this.country);
}
updateCity(city){
this.city = city;
}
}
我只在第一次选择时获得国家和城市参数。如果我从下拉列表中选择其他选项,它不会更新国家和城市。
试图在app.component.html上看到这样的,它的更新在这里。
<p>Selected country: {{ country }}</p><br>
<p>Selected city: {{ city }}</p>
例如-
第一次,如果我从国家中选择“美国”,从城市中选择“纽约”。它的传递参数正确。
第二次如果我将城市更改为“奥斯汀”,它不会将“奥斯汀”传递给组件(城市值不会更新/更改)。
请帮助/指导。
解决方案
您的样品工作正常。只需添加以下代码render.component.html
即可查看绑定是否正常工作
{{ 国家城市 }}
供您参考,ngOnInit
仅在第一次初始化组件时运行(在您的情况下第一次选择城市时)。它不会在每次绑定更改时触发。要记录每个绑定更改,您应该console.log
在ngOnChanges()
lifehook中添加
更新了 StackBlitz 上的示例以说明:https ://stackblitz.com/edit/angular-zbzahn
推荐阅读
- python-3.x - 如何将excel内容转换为python字典
- java - 需要在java中的方法内的字符串中添加默认值
- sql-server - 如何在 SQL Server 中查找两个不同日期之间的天数?
- python - 无法使用请求库 python 检索 api 令牌
- c# - EPPlus:复制现有 Excel 工作表时无法访问已关闭的 Stream
- c++ - 这个 C 函数有什么类型的函数参数声明?
- c# - 右键单击单元格文本启用 C# Excel 插件功能区
- bash - 如果文件在 N 秒内没有更改,取消“tail -f”?
- java - Android Studio:消息“在项目结构对话框中配置项目”
- jenkins - Nexus NPM 存储库