簡體   English   中英

何時調用ngOnInit方法?

[英]When is ngOnInit method called?

我有以下模板

<div *ngIf="hotels$ | async as hotels; else loadGif ">
   <div *ngFor="let hotel of hotels | hotelsFilter: _filteredType; first as f; index as i " 
    appInit [hotel]="hotel " [first]="f ">
    <app-card appHighlight [hotel]=hotel></app-card>
   </div>
</div>

並在過濾列表后編寫appInit指令以識別酒店列表的第一元素。 這是appInit指令的ngInit方法:

  constructor(
        private __hotelsService: HotelsService
      ) { }

      @Input()
      public hotel: Hotel;
      @Input()
      public first: boolean;

      public ngOnInit(): void {
        if (this.first) {
          this.__hotelsService.selectedHotel$.next(this.hotel);
          console.log('first init ' + this.hotel.name);
        }else{
          console.log('not first init ' + this.hotel.name);
        }

      }

問題是該指令的ngOnInit方法不會在每次篩選並重新呈現酒店列表時都調用。 問題是,為什么以及何時真正應該調用ngOnInit?

每次運行變更檢測並更新具有綁定到它們的值的輸入時,就會調用ngOnChanges
在調用ngOnInit之后第一次調用ngOnChanges

有關更多詳細信息,請參見https://angular.io/guide/lifecycle-hooks

*ngFor渲染元素時,它將識別何時值相同,並重新使用渲染的項目。 這就是為什么ngOnInit在過濾器更改之前也已呈現的項目,在過濾器更改之后不調用ngOnInit原因。

您可以改用ngOnChanges ,每次更新輸入時都會調用ngOnChanges ,也可以使輸入獲取器

  _first: boolean,
  @Input()
  public set first(value: boolean) {
    this._first = value;
    if (this.first) {
      this.__hotelsService.selectedHotel$.next(this.hotel);
      console.log('first init ' + this.hotel.name);
    }else{
      console.log('not first init ' + this.hotel.name);
    }
  }

  public get first() : boolean {
    return this._first;
  }

初始化組件時,只會調用一次ngOnInit 根據您的需要,您應該使用ngOnChanges ,當輸入屬性被更改時將被調用。

有關生命周期掛鈎的更多信息: https : //angular.io/guide/lifecycle-hooks

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM