【问题标题】:Prevent error while radio value change while load component in Angular在Angular中加载组件时防止无线电值更改时出错
【发布时间】:2021-03-25 16:51:33
【问题描述】:

请帮助我,我尝试使用单选按钮来设置日期,但是在加载组件时更改值时出错。

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;
}
...

使用这个我得到了错误:

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)

请帮助解决这个错误。

【问题讨论】:

  • 为什么不能将 asPeroidBtn 的值默认设置为 '1M'?
  • @PiyushJain 我有其他理由默认设置此 '1W' ,但在某些情况下我需要设置它 '1M' ,但如果我将它设置为 '1M',它就会出错。

标签: javascript angular typescript radio-button


【解决方案1】:

ngAfterViewInit改成ngAfterContentInit就不会出现错误了。

有关更多信息,请在此处查看此答案

ExpressionChangedAfterItHasBeenCheckedError Explained

【讨论】:

  • 感谢您的回答,太好了
猜你喜欢
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 2015-11-06
  • 2023-01-10
  • 1970-01-01
  • 2019-06-22
  • 2019-10-08
  • 2021-01-29
相关资源
最近更新 更多