Change detection does not trigger when the formgroup values change

前端 未结 4 625
我在风中等你
我在风中等你 2021-01-11 19:12

I have created a simple example to demonstrate a weird issue I\'m facing.

Stackblitz - https://stackblitz.com/edit/angular-change-detection-form-group

I hav

4条回答
  •  一生所求
    2021-01-11 19:47

    During the automatic change detection (cd) run Angular would notice that the values of your FormGroup have been updated and updates the UI respectively.

    By setting the change detection strategy to OnPush you deactivates the automatic change detection run by Angular. In this case only the internal values are updated, but Angular would not check the values of the UI.

    Maybe this is a too superficial explanation of Angular's ChangeDetection, so I recommend this blog for a deeper look into this topic.

    ngOnChanges does not trigger, because the object reference (memory address) of your FormGroup has not been changed. ngOnChanges is only triggered if you pass primitives to the @Input of your components. And this would also trigger a new change detection run by Angular.

    To update the UI you can trigger the change detection manually by injecting ChangeDetectorRef in your parent component and calling detectChanges().

    This could look like this:

    constructor(private cd: ChangeDetectorRef) {}
    ...
    changeFormValue() {
        this.form.setValue({
            name: 'XYZ',
            age: 35
        });
        // This will trigger the change detection and your input field are updated
        this.cd.detectChanges(); 
    }
    

    I hope this is understandable ;-)

提交回复
热议问题