Angular - How to fix the issue of Async pipe not updating the View after AfterViewInit emits a new value

I have a straightforward component that contains a BehaviorSubject. Within my template, I utilize the async pipe to display the most recent value from the BehaviorSubject.

When the value is emitted during the OnInit lifecycle hook, the view updates correctly with the new value. However, when I emit a value during the AfterViewInit hook, the async pipe does not update the view.

Is this behavior expected? Why does the async pipe fail to update the second emitted value?

Below is an example of the component code:

@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 value 100
    this.test$.next(100);
  }

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

And here's an example of the component template:

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

Answer №1

When utilizing the OnPush change detection strategy, it is important to manually trigger a check for changes:

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

The ngOnInit function is executed before the view is checked, displaying 100 initially.

ngAfterViewInit occurs after the initial view check when using the OnPush change detection strategy, requiring manual triggering of changes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My project encountered an error when trying to serve with Angular-cli (property 'slice' of null cannot be read)

Everything was running smoothly with my project until now, but after making some modifications to a node_modules file, I encountered an issue. Whenever I attempt to use the "ng" command, I receive the following error message: /usr/lib/node_modules/angula ...

Vue version 3 is encountering an issue with a module that does not have an exported member in the specified path of "../../node_modules/vue/dist/vue"

After I updated my npm packages, errors started popping up in some of the imports from the 'vue' module: TS2305: Module '"../../node_modules/vue/dist/vue"' has no exported member 'X' The X instances affected inclu ...

How to assign ngModel to a nested component in Angular?

If I have a component called InputComponent, which implements the ControlValueAccessor interface. Now, another component named AnotherComponent uses the InputComponent like this: <my-input [(ngModel)]="text"></my-input> While testing AnotherC ...

Learn how to host a singular instance of an Angular application for every unique route, similar to the setup utilized in meet.jit.si

Is there a way to create an Angular app that loads a new instance of itself on every route/url? For example, visiting http://happy-app.com/happy would show the app in one state, and going to http://happy-app.com/happier would load the same app in a differe ...

Storing Angular header values in local storage

saveStudentDetails(values) { const studentData = {}; studentData['id'] = values.id; studentData['password'] = values.password; this.crudService.loginstudent(studentData).subscribe(result => { // Here should be the val ...

"Is There a Specific Order for Organizing Angular Router

Could you please clarify the difference between these two code snippets? const routes: Routes = [ { path: '', canActivate: [AuthGuard], component: MainComponent, children: [ { path: '', component: DashboardComponent }, ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

The error message "TypeError: Attempting to access the 'map' property of an undefined value (React JS)" was displayed

I'm currently working on a recursive function that needs to iterate over an object type called ItemType. However, I encountered an error message: TypeError: Cannot read property 'map' of undefined This is the code snippet causing the issue: ...

Do type declaration files for NPM packages have to be in the .d.ts format?

I believe it is feasible to include type declarations in any typescript file like '.d.ts', '.ts', or '.tsx'. However, I have observed that the type declaration files for most npm packages are .d.ts files. Is this a requireme ...

"Navigate to another screen with the FlatList component upon press, displaying specific

I've created a flatlist of countries with a search filter using an API. I need help implementing a feature where clicking on a country's name in the list redirects to a screen that displays the country's name and number of cases. The screen ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

How to assign multiple values within nested for loops in Angular 6

I am facing an issue with my template file where I have two loops. I am attempting to bind the second value using the first loop value, but I am encountering an error. <tr *ngFor="let splitdata of mf.data"> <td *ngFor="let slitup of searchFie ...

The functionality of MaterializeCSS modals seems to be experiencing issues within an Angular2 (webpack) application

My goal is to display modals with a modal-trigger without it automatically popping up during application initialization. However, every time I start my application, the modal pops up instantly. Below is the code snippet from my component .ts file: import ...

The SpinButton object has an undefined public property called 'value' and the public method 'focus()' is not available

Recently, I've delved into using reactjs, typescript, and Office UI Fabric. However, I'm facing a challenge with one of the components from fabric. In this scenario, I have a simple Product component containing a SpinButton and a DefaultButton. M ...

Tips for assigning a JSON object as the resolve value and enabling autosuggestion when utilizing the promise function

Is there a way to make my promise function auto-suggest the resolved value if it's a JSON object, similar to how the axios NPM module does? Here is an example of how axios accomplishes this: axios.get("url.com") .then((res) => { Here, axios will ...

Encountering RxJS errors during the process of constructing an object using streams retrieved from Firebase

I am currently in the process of developing a template-driven form that involves multiple streams from Firebase. Despite my efforts, I keep encountering errors with the json pipe. The error message I receive is "Converting circular structure to JSON as ...

Is it possible to execute an HTTP request using a functional resolver?

Previously, I used a class-based resolver where I could inject HttpClient in the constructor. However, this approach has now been deprecated - see the source for more information. Now, I am looking to implement an HTTP get request in a functional resolver ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...

Resolving the CORS predicament caused by the ionic/angular's HTTP interceptor

I am currently using Ionic for both web and mobile development. However, I have encountered a CORS issue when integrating it with an HTTPS URL. Interestingly, the issue seems to be resolved after removing the HTTP interceptor. Nevertheless, I am seeking a ...

Exploring the attributes of a record through a combination of string template types

I'm utilizing a string template type to denote ids with a significant prefix, such as dta-t-${string} where dta-t- encodes certain details about the entity. I have various record types that are indexed by unions of string templates: type ActivityTempl ...