首页 > 解决方案 > 下拉更改后组件参数不变

问题描述

我有以下基于下拉菜单的下拉代码。

<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>

例如-

第一次,如果我从国家中选择“美国”,从城市中选择“纽约”。它的传递参数正确。

第二次如果我将城市更改为“奥斯汀”,它不会将“奥斯汀”传递给组件(城市值不会更新/更改)

请帮助/指导。

标签: angular

解决方案


您的样品工作正常。只需添加以下代码render.component.html即可查看绑定是否正常工作

{{ 国家城市 }}

供您参考,ngOnInit仅在第一次初始化组件时运行(在您的情况下第一次选择城市时)。它不会在每次绑定更改时触发。要记录每个绑定更改,您应该console.logngOnChanges()lifehook中添加

更新了 StackBlitz 上的示例以说明:https ://stackblitz.com/edit/angular-zbzahn


推荐阅读