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

Experience the quirk of using Angular's mat-button-toggle-group with the multiple attribute, and uncover the

I'm experiencing a strange issue with the mat-button-toggle. Here is the code snippet: <mat-button-toggle-group formControlName="fcCWShowForms" multiple="true"> <mat-button-toggle value="HE" (change)="this.showHe=!this.showHe"> Button ...

Ensuring the Current Page is Valid Before Progressing to the Next Step in Angular-Archwizard

Currently, I am working with Angular-7 and using angular-archwizard to create a multi-step form. The issue I am facing is that the form allows users to proceed to the next step without filling in all the required fields. My goal is to restrict users from m ...

Issue encountered in Loopback 4: Error with @repository dependency injection (TypeError: Undefined property 'findOne')

As I set up Bearer Token authentication for my Loopback 4 application, I referenced this implementation guide: https://github.com/strongloop/loopback-next/tree/master/packages/authentication. Within my src/providers/auth-strategy.provider.ts file, I encou ...

Guide on setting up global typing for AngularJS in your project

I have been working on a project that initially used the deprecated typings method for incorporating Typescript definitions. I now want to transition to using the @types method instead. Currently, we have a typings.json file located in the root of the pro ...

When it comes to form validations, I encounter an issue. I am able to view errors.minlength in the console, but for some reason, I am unable to access it

I would like the message "name is too short" to be displayed if last_name.errors.minlength evaluates to true. However, I encounter an error: Property 'minlength' comes from an index signature, so it must be accessed with ['minlength']. ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

prolonging inner interface created by supabase

Below is the Typescript interface that has been generated by Supabase export interface definitions { Users: { /** Format: uuid */ id: string; /** * Format: timestamp with time zone * @default now() */ created_at?: string; ...

Build a unique array of identifiers extracted from an object

I am seeking advice on how to extract an array of IDs values by iterating through an object in React JS. const initialState = useMemo(()=> { return dataTable.filter(result => favorites.some(favorite => result.id === favorite.id)) },[ ...

Having trouble locating the term 'xdom2jso' while implementing Angular2-Soap within Ionic 2

Encountering an issue while trying to use Angular2-Soap in Ionic 2. I added Angular2-Soap to my Ionic 2 blank project by running the command: sudo npm install autopulous-angular2-soap In the home.ts {Start Page} file, I included the following line of cod ...

Angular: Creating an instance of a class with StaticProvider passed as a parameter

Having trouble instantiating a class with a StaticProvider. Here's the code snippet: main.ts export function createProvider() { // some implementation return result; // result is a string } const providers = [ { provide: 'TEST' ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

RxJS mergeMap waits for the completion of inner Observables before moving on to

I encountered an issue with my solution that initially appeared to be working, but when tested on a slow network: public getKeyFigureValuesForAllClients(keyFigurename: string) { const keyFigureDefintion$ = this.keyFigureDefintions$.pipe( flatMap ...

Export an array of objects using the Angular XLSX library

Here is my example data: exampleData: any[] = [ { "id": "123", "requestType": "Demo", "requestDate": "12/05/21", "status": "Success", "product": [ { "productName": "example product A", "productQty": "8" ...

I am seeking a way to manipulate two arrays simultaneously using a single ngFor loop within the <tr> element

<tr *ngFor="let element of serialNo,listArray"> <td class="text-center"> {{element}}</td> <td class="text-center"> {{element.title}}</td> </tr> I am look ...

Facing a Timeout Issue while Testing an Angular application using Protractor

When working with an Angular application and setting browser.waitForAngularEnabled(true), I encountered the following error after clicking on an element: ScriptTimeoutError: script timeout (Session info: chrome=85.0.4183.121) Driver info: chromedriver=85.0 ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

Prevent specific dates on Angular Mat Calendar by utilizing Rest API response

I am currently working with the Angular material calendar, specifically the mat-calendar component. My goal is to dynamically disable certain dates in the calendar based on specific values. HTML <mat-calendar [headerComponent]="exampleHeader" [dat ...

Steps for creating user accounts and saving user information in Firebase's Real Time Database

Can someone please guide me on how to register a user in Firebase and save their additional details such as first name, last name, etc.? I have created a standard registration form in Angular and successfully registered users with their username and pass ...

Mastering the art of constraining TypeScript function parameters using interface properties

Hey there, I've been exploring ways to restrict a function parameter so that it only accepts "strings" related to interface properties, similar to what I achieved in the validate fields function: Please note: The TypeScript code provided here is simp ...