[英]ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined' Exception
I know this has been asked many times, but after reading similar problems I'm still unable to organize my code to fix this exception,我知道这已经被问过很多次了,但是在阅读了类似的问题之后,我仍然无法组织我的代码来修复这个异常,
in my component I have this property that change dynamically based on a condition在我的组件中,我有这个根据条件动态变化的属性
public emailToValue: string
in my html在我的 html
the user can manually add a new row and then I call a pipe to set the value assigned in the component用户可以手动添加一个新行,然后我调用一个管道来设置组件中分配的值
<ng-container matColumnDef="emailTo">
<mat-header-cell *matHeaderCellDef mat-sort-header>Email To</mat-header-cell>
<mat-cell *matCellDef="let userMarket">
{{ userMarket | formatEmailTo : emailToValue}}
<input type="text" matInput [value]="userMarket.emailTo">
</mat-cell>
</ng-container>
this is my pipe, if the email is null or undefined I set by default an email to be displayed in the new row这是我的管道,如果电子邮件为空或未定义,我默认设置电子邮件显示在新行中
@Pipe({
name: 'formatEmailTo',
})
export class FormatEmailPipe implements PipeTransform {
public transform(userMarket: UserMarketDTO, email: string): void {
if (_.isNil(userMarket.emailTo)) {
userMarket.emailTo = email;
}
}
}
functionality is working but Im getting this exception every time that I create a new row功能正在运行,但我每次创建新行时都会收到此异常
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'value: undefined'. Current value: 'value: suport@support.com'.
I would appreciate any help我将不胜感激任何帮助
thanks谢谢
A couple points here:这里有几点:
undefined
would have been the value on the front end in production.当您收到该错误时,这意味着undefined
第一个值将是生产中前端的值。But assuming there's some requirement forcing you to do it this way and you want to avoid using the ChangeDetectorRef, I think I have a solution for you.但是假设有一些要求迫使你这样做,并且你想避免使用 ChangeDetectorRef,我想我有一个解决方案。 Please see my stackblitz :请看我的stackblitz :
Use a template ref for the column with an already piped UserMarketDTO
:使用已通过管道传输的UserMarketDTO
列的模板引用:
<ng-template #emailCell let-userMarket>
{{ userMarket.email }}
<input type="text" matInput [value]="userMarket.email">
<ng-template>
And the column definition where the piping happens:以及管道发生的列定义:
<!-- Email Column -->
<ng-container matColumnDef="email">
<th mat-header-cell *matHeaderCellDef> Email </th>
<td mat-cell *matCellDef="let element">
<ng-container *ngTemplateOutlet="emailCell; context: { $implicit: element | formatEmailTo: defaultEmailValue }"></ng-container>
</td>
</ng-container>
But this also requires updating the pipe to return the UserMarketDTO
:但这也需要更新管道以返回UserMarketDTO
:
public transform(userMarket: UserMarketDTO, defaultEmail: string): UserMarketDTO {
if (!userMarket.email) {
userMarket.email = defaultEmail;
}
return userMarket;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.