Angular는 두 가지 변경 감지 전략을 제공합니다: Default와 OnPush.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>{{counter}}</p><button (click)="increment()">Increment</button>`,
})
export class ExampleComponent {
counter = 0;
increment() {
this.counter++;
// 이 시점에서 Angular는 데이터 바인딩된 `counter` 값이 변경되었음을 알아채고 화면에 반영합니다.
}
}
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl:'./child.component.html',
changeDetection : ChangeDetectionStrategy.OnPush,
})
export class ChildComponent{
@Input() data : any;
}
위 코드에서 ChildComponent은 부모로부터 @Input 프로터리인 data를 받습니다. 여기서 Onpush전략은 부모component 에서 넘어오는 @input값(data) 가 바뀔경우에만 view 를 update 해줍니다.
참고: 양방항 데이터 바인딩([(ngModel)])과 같은 디렉тив들도 동일하게 동작하여 해당 변수 값이 달라질 때마다 DOM 요소 값을 다시 그립니다.
Angular 애플리케이션 성능 최적화 관점에서 보았을 때 "OnPush" 전략 사용하는 것은 좋습니다 . 왜냐하면 필요할 때만 DOM 업데이팅하기 때문입니다.
그러나 "OnPush" 사용시 주의사항도 있으니 잘 고려해서 사용해야 합니다.
많은 도움이 되었습니다, 감사합니다.