简体   繁体   中英

Angular child update parent and ExpressionChangedAfterItHasBeenCheckedError

So I understand the 'why' of getting the ExpressionChangedAfterItHasBeenCheckedError on Angular, but I just can't figure out how to fix it based on the articles I'm reading. What I have is a service that defines an observable like so:

private classification = new BehaviorSubject<string>('Assumed to be A');
public hazardClassification$ = this.classification.asObservable();

public setClassification(value: string): void {
    this.classification.next(value);
}

In the child component, which is where I determine the value, I'm setting it from the ngOnInit :

ngOnInit(): void {
    this.hazardClassificationService.setClassification(this.hazardClassification);
    this.valueChanges = this.thisTabFormGroup.valueChanges.subscribe(() => this.hazardClassificationService.setClassification(this.hazardClassification));
}

In the parent component I grab that observable like so:

ngAfterContentChecked(): void {
    this.hazardClassification$ = this.hazardClassificationService.hazardClassification$;
}

and then display it in the parent's HTML via hazardClassification$ | async hazardClassification$ | async .

What I've tried so far is assigning the observable, in the parent, in ngOnInit , ngAfterContentChecked and ngAfterContentInit . None of them are the right spot.

Try to call this.classification.next(value) inside setTimeout :

public setClassification(value: string): void {
    setTimeout(() => {
        this.classification.next(value);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM