【问题标题】:ngOnChanges is not triggered when value changes from select当值从选择更改时,不会触发 ngOnChanges
【发布时间】:2017-11-28 00:51:49
【问题描述】:

我有下一个 html:

<select  [(ngModel)]="district"  class="form-control" (change)="dsChange()">

      <option disabled hidden [value]="undefined" >Ноҳия</option>

      <option *ngFor="let dis of districts" [ngValue]="dis">{{dis.title}}</option>
</select>

我还有下一个组件

@Input() district: District;
 ngOnChanges(changes: SimpleChanges) {
      console.log("CHANGED")
}
 dsChange(){
      console.log(this.district);
}

我不明白为什么当我选择一些值时,dsChange 会触发正确的区值,但 ngOnChanges() 不是

【问题讨论】:

  • 为什么要近距离投票?有人可以解释一下吗
  • 这与组件之间的交互有关,这就是@Input和@Output的使用情况,在这里介绍:angular.io/guide/component-interaction

标签: angular angular2-template ngonchanges


【解决方案1】:

即使变量是组件的本地变量,它也不会调用 onChanges。我为此创建了一个 plukr:

https://plnkr.co/edit/lsqyeZ8aiBpylciOQxnU?p=preview

【讨论】:

    【解决方案2】:

    ngOnChanges 在组件的数据绑定输入属性更改时调用。在您的情况下,如果父组件为 @Input() district 设置新值,它将被调用。

    See the docs

    ngOnChanges()

    在 Angular(重新)设置数据绑定输入属性时响应...在 ngOnInit() 之前以及一个或多个数据绑定输入属性更改时调用。

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 2018-01-20
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多