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與組件是否進行變化檢測沒有直接關系。