首页 > 解决方案 > ngOnChanges 只执行一次

问题描述

我在我的子组件中使用了 ngonchange,如下所示。但我看到它只执行一次。所以基本上我的子组件中有一个下拉列表,所以当我在下拉列表中更改某些内容时,我希望执行 ngonchange,这只会发生一次。我第二次更改项目时,ngonchange 没有被执行。

ngOnChanges(changes: SimpleChanges){
  console.info(changes.test);
  if(this.test!=null){
    console.info(this.test);
    this.currentSnapshotPeriod = this.snapshotPeriods.filter(x => x.periodName === this.test)[0];
 this.onCurrentSnapshotPeriodChange();
 changes.SimpleChanges.currentValue = undefined;
  }
}

父 HTML:

<app-snapshot-period-dropdown
                       [test]=input
                         (change)="abc($event)"
                        >
                    </app-snapshot-period-dropdown>

子 HTML :

<select
      id="currentPeriodDropDown"
      (change)="onCurrentSnapshotPeriodChange()"
      [(ngModel)]="currentSnapshotPeriod"
      class="form-control form-control-sm mr-1 form-control-sm-ipad"
    >
      <option [ngValue]="period" *ngFor="let period of snapshotPeriods"
        >{{ period?.periodName }}
      </option>
    </select>

标签: angulartypescriptangular8

解决方案


ngOnChanges 仅在 @Input() 从父组件更改时触发,而不是在您在子组件中更改它时触发。这是我犯的错误


推荐阅读