简体   繁体   中英

Angular - Async pipe not updating View when AfterViewInit emits a new value

I have a simple component which holds a BehaviorSubject . In my template I use async pipe to update the view and get the latest value from my BehaviorSubject .

When the value is emitted from OnInit lifecycle hook, the async pipe updates the view with the correct value. But when I try to emit a value from AfterViewInit , the async pipe does not update the view.

Is this correct behavior? Why async pipe won't update the second emitted value?

Example component:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent implements OnInit, AfterViewInit {
  
  public test$ = new BehaviorSubject(0);

  constructor(public cd: ChangeDetectorRef) {
    // All three values are logged - 0, 100, 200
    this.test$.subscribe(console.log);
  }

  ngOnInit() {
    // View is updated with 100 value
    this.test$.next(100);
  }

  ngAfterViewInit() {
    // View is not updated, async pipe is not triggered
    this.test$.next(200);
  }
}

Example component template:

<h1>{{ test$ | async }}</h1>

You are using OnPush change detection strategy. You should trigger check for changes manually:

ngAfterViewInit() {
    // View is not updated, async pipe is not triggered
    this.test$.next(200);
    this.cd.detectChanges();
}

ngOnInit is called before a view is checked. so 100 will be displayed at first.

ngAfterViewInit is called after an initial check for your view has been done. Since you are using OnPush change detection strategy, it will not trigger a change automatically.

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