【问题标题】:Component Parameter does not change after dropdown change下拉更改后组件参数不变
【发布时间】:2019-10-16 08:04:11
【问题描述】:

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

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

举例 -

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

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

请帮助/指导。

【问题讨论】:

  • 你能在stackbiltz中分享吗
  • @TheNsn666 尝试(更改)事件,没有运气。

标签: angular


【解决方案1】:

在我看来,一切都在你的堆栈闪电战中正常运行。 如果你想看到控制台中的变化,你应该把日志放到ngOnChanges()

import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'app-render',
  templateUrl: './render.component.html',
  styleUrls: ['./render.component.css']
})
export class RenderComponent implements OnChanges {

  @Input()
  public country: String;

  @Input()
  public city: String;


  constructor() { }

  ngOnChanges() {
    console.log("country : ", this.country);
    console.log("city : ", this.city);
  }

}

这样,每次您的城市我们的国家@Input 更新时,控制台都会记录。

【讨论】:

  • 已解决。非常感谢。
【解决方案2】:

您的示例运行良好。 只需在render.component.html 中添加以下代码即可查看绑定是否正常工作

{{ 国家 }} -- {{ 城市 }}

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

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

【讨论】:

  • 完美! 解释得很好。
  • 已解决。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 2021-08-25
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多