我有以下组件:
客户card.component.html:
<div id="content">
<div id="card" (click)="viewDetails(client.clientId)">
<div id="front">
<div id="top-pic" [ngClass]="setTopPic()"></div>
<div id="avatar"></div>
<div id="info-box" [class.green]="(i + 1) % 2 == 0" [class.blue]="(i + 1) % 2 != 0">
<div class="info">
<h1>{{ client.surname }}, {{ client.forename }}</h1>
<h2>{{ client.postcode }}</h2>
</div>
</div>
</div>
</div>
客户card.component.ts:
import { Router } from '@angular/router';
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-client-card',
templateUrl: './client-card.component.html',
styleUrls: ['./client-card.component.css']
})
export class ClientCardComponent implements OnInit {
@Input() client: any = {};
@Input() i: number;
constructor(private router: Router) { }
ngOnInit() {
console.log(`Init Card Component`)
}
viewDetails(clientId: number) {
this.router.navigate(['/client', clientId]);
}
setTopPic() : string {
if((this.i + 1) % 2 == 0) {
return "blue" + Math.ceil(Math.random() * 4).toString();
} else {
return "green" + Math.ceil(Math.random() * 4).toString();
}
}
}
客户list.component.html:
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3" *ngFor="let client of clients; let i = index">
<app-client-card [client]="client" [i]="i"></app-client-card>
</div>
</div>
每当客户端列表组件显示卡片时,我在控制台中收到以下错误:
错误错误:ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改。上一个值:'blue1'。当前值:'blue2'。
我已经阅读了关于此错误的各种原因的一些不同解释,但遗憾的是没有更接近解决它。
非常感谢任何帮助。
答案 0 :(得分:0)
通常在非生产模式下运行时会出现此错误,原因是更改检测运行两次,以检查代码中是否存在修改区域外数据的错误。
这里发生的是您的方法foreach($Pull_ListSpecProp_RQ->Property->Amenities->Amenity as $AmenityID){
foreach ($Pull_ListAmenities_RQ->Amenities->Amenity as $Amenity) {
if ($AmenityID->__toString() === $Amenity->attributes()->AmenityID->__toString()) {
echo $Amenity->__toString() . "<br>";
}
}
}
每次调用时都可能返回不同的值,因此更改检测在检查绑定时会看到setTopPic()
,之后会看到blue1
。
我建议将类名存储在init的成员变量中,因为它依赖于你的其他成员变量blue2
:
i
并在绑定中使用它:
export class ClientCardComponent implements OnInit {
@Input() client: any = {};
@Input() i: number;
topPic: string;
constructor(private router: Router) { }
ngOnInit() {
console.log(`Init Card Component`);
this.topPic = setTopPic(); // <-- here
}