Home > Net >  Using Angular ngStyle with ChangeDetectionStrategy.OnPush?
Using Angular ngStyle with ChangeDetectionStrategy.OnPush?

Time:10-15

This stackblitz demo is using ngStyle to style the h1 element like this:

<h1 [ngStyle]="{'background-color':backgroundColor}"

The HelloComponent also uses OnPush change detection strategy:

@Component({
  selector: 'hello',
  template: `<h1 [ngStyle]="{'background-color':backgroundColor}">Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})

When the background color is updated to yellow in ngAfterViewInit() the view does not update and the color remains as blue.

How do we trigger change detection, such that the style will update?

I tried this.cdr.markForCheck() to see if I could trigger it.

CodePudding user response:

Console of your stackblitz says ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'blue'. Current value: 'yellow;'..

You simply have a typo. Change

this.backgroundColor = 'yellow;'

to

this.backgroundColor = 'yellow';

(move semicolon to outside the string value)

  • Related