angular中ngOnChanges與組件變化檢測的關系


1.ngOnChanges只有在輸入值改變的時候才會觸發,如果輸入值(@Input)是一個對象,改變對象內的屬性的話是不會觸發ngOnChanges的。

2.組件的變化檢測:

  2a.changeDetection如果是ChangeDetectionStrategy.Default的話,無論輸入值(@Input)是否發生變化,都會進行組件自身的變化檢測。

  2b.changeDetection如果是ChangeDetectionStrategy.OnPush的話,只有在輸入值(@Input)發生變化的情況下,才會進行自身的變化檢測。

  因此OnPush的組件在其內部改變屬性值是不會反應在頁面上的

@Component({
  selector: 'app-movie',
  template: `
    <div>
      <h3>{{ title }}</h3>
      <p>
        <label>Actor:</label>
        <span>{{actor.firstName}} {{actor.lastName}}</span>
      </p>
      <div>{{test}}</div>
    </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MovieComponent implements OnInit {
  @Input() title: string;
  @Input() actor: Actor;
  test = 'test';

  constructor(private cd: ChangeDetectorRef) {}

  ngOnInit(): void {
    setTimeout(() => {
      this.test = 'test1';
      this.cd.detectChanges();
    }, 1000);
  }
}

這種情況要使用ChangeDetectorRef的detectChanges方法手動啟用組件的變化檢測。

  2c.ChangeDetectorRef.detach之后的組件是不會在變化檢測周期里自動進行變化檢測的,需要手動進行變化檢測。

3.組件的DoCheck接口無論什么情況都會在變化檢測周期被調用。

以上可知,ngOnChanges與組件是否進行變化檢測沒有直接關系。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM