0

Please help me I try to use radio button to set date but it got error when I change value while component load.

html.component.html

...
<div>
    <input type="radio" name="period" [checked]="asPeroidBtn === '1W'" (click)="setDate( '1W' )"/><span>1 Week</span>
    <input type="radio" name="period" [checked]="asPeroidBtn === '1M'" (click)="setDate( '1M' )"/><span>1 Month</span>
    <input type="radio" name="period" [checked]="asPeroidBtn === '3M'" (click)="setDate( '3M' )"/><span>3 Months</span>
    <input type="radio" name="period" [checked]="asPeroidBtn === '6M'" (click)="setDate( '6M' )"/><span>6 Months</span>
</div>
...

html.component.ts

...
asPeroidBtn = '1W';
...
ngAfterViewInit() {
    this.setDate('1M');
}

setDate(period){
    this.asPeroidBtn = period;
}
...

By using this I got error:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'checked': 'true'. Current value: 'false'.
    at throwErrorIfNoChangesMode (core.js:5625)
    at bindingUpdated (core.js:13962)
    at Module.ɵɵproperty (core.js:14706)
    at GNB5100Component_Template (html.component.html:36)
    at executeTemplate (core.js:7449)
    at refreshView (core.js:7318)
    at refreshComponent (core.js:8465)
    at refreshChildComponents (core.js:7126)
    at refreshView (core.js:7368)
    at refreshEmbeddedViews (core.js:8419)

Please help how to fix this error.

Traly
  • 67
  • 9
  • why can't you set asPeroidBtn value as '1M' by default ? – Piyush Jain Dec 15 '20 at 03:43
  • @PiyushJain I have other reason to set this **'1W'** by default, but in some case I need to set it **'1M'** , but It got error in case I set it to **'1M'**. – Traly Dec 16 '20 at 03:04

1 Answers1

1

change from ngAfterViewInit to ngAfterContentInit and the error will not occurred.

for more information check this answer here

ExpressionChangedAfterItHasBeenCheckedError Explained

Luay AL-Assadi
  • 426
  • 7
  • 16