![](/img/trans.png)
[英]ExpressionChangedAfterItHasBeenCheckedError in ngIf?
[英]ExpressionChangedAfterItHasBeenCheckedError . Angular 2(5) *ngIf
我正在使用一项服务在子与父之间传递数据,目的是根据子加载的具体情况,使用子特定信息更新父ui。
服务:
import { Subject } from "rxjs/Subject";
export class ChildDataService {
private childDetails = new Subject<{}>();
childLoaded$ = this.childDetails.asObservable();
changedComponentName(option: {}){
this.childDetails.next(option);
}
}
父组件:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ChildDataService } from "../core/helpers/child-data.service";
import { Subscription } from "rxjs/Subscription";
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
childDetails: {title?: string};
private subscription:Subscription;
constructor( private childDataService: ChildDataService) {
this.childDataService.childLoaded$.subscribe(
newChildDetails => {
console.log(newChildDetails);
this.childDetails = newChildDetails
});
}
}
子组件示例:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ChildDataService } from "../../core/helpers/child-data.service";
@Component({
selector: 'app-child-dashboard',
templateUrl: './child-dashboard.component.html',
styleUrls: ['./child-dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ChildDashboardComponent implements OnInit {
constructor(private childDataService: ChildDataService) { }
public ngOnInit() {
this.childDataService.changedComponentName({
title: 'Dashboard'
});
}
}
父HTML:
<div class="subheader">
<h1>{{ childDetails?.title }}</h1>
<button *ngIf="childDetails?.title == 'Dashboard'">dashboard</button>
<button *ngIf="childDetails?.title == 'SecondChild'">Second Child</button>
</div>
通过此设置,当我单击routerLink时,出现错误“ ExpressionChangedAfterItHasBeenCheckedError”,现在,如果第二次单击同一链接,该错误仍然存在,但正确的按钮变为可见。 整个周末都花了很多钱,所以任何帮助将不胜感激。
public ngOnInit() {
setTimeout(() => {
this.childDataService.changedComponentName({
title: 'Dashboard'
}), {});
}
它应该工作。
async ngOnInit() {
await this.childDataService.changedComponentName({
title: 'Dashboard'
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.