【发布时间】:2018-09-13 01:11:31
【问题描述】:
演示可在此处获得 - https://stackblitz.com/edit/angular-a9wcee
请打开控制台窗口查看错误。
说明
我有一个Bootstrap 组件ComponentA,它应该根据应用程序的启动过程以两种不同的方式启动。假设应用程序是使用 url home.com 启动的,那么 ComponentA 在启动时不应该显示弹出对话框,但如果应用程序是使用 home.com;signup 启动的,那么应用程序应该会显示一个弹出窗口。
我读到Input 不适用于引导组件,因此我将index.html 中的属性作为“启动上下文”传递给ComponentA。
<comp-a someAttr="someValue"></comp-a> <!--depending on whether someAttr is empty ("") or not, the pop should not be shown or shown respectively -->
而ComponentA 在其模板中使用DialogComponent,如下所示
<comp-dialog [message]=""></comp-dialog> <!-- I want the input to ComponentB to be empty to begin with -->
ComponentB 是一个Bootstrap css 对话框,并在对话框可见时显示Input 消息。棘手的一点是ComponentB 在ComponentA 的模板中,因此Angular 将其初始化为ComponentA 启动的一部分,但在ComponentA 启动完成之前,ComponentA 尝试更改@987654343 @(message 属性)如果它确定它必须显示对话框(ComponentB)(通过检查属性)。我认为这与Change Detection 产生了问题,而我Angular 正在抛出ExpressionChangedAfterItHasBeenCheckedError 错误。如何重新设计组件交互
ComponentA的代码sn-ps是
-
检查我是如何开始的。
ngAfterViewChecked(){ this.signup = this.el.nativeElement.getAttribute('signup'); //get the attribute this.isSignupProcess();//check if ComponentB needs to be shown and update its message property } isSignupProcess(){ console.log("sign up is "+this.signup) if(this.signup!==""){ //show ComponentB if(this.signup === "success") { this.showDialog("Signup was successful",new DialogContext("","")) //set message property of ComponentB }else if(this.signup === "error") { this.showDialog("Error: Signup wasn't successful",new DialogContext("","")) } else { this.showDialog("Unrecognised message: "+this.signup,new DialogContext("","")) } this.signup = ""; //no need to show ComponentB } else { }}
更新ComponentB 的message 属性并显示它的逻辑
showDialog(message:string,context:DialogContext) {
this.dialogComponent.dialogShow(message,context);
}
ComponentB 只是调用Bootstrap 的模态函数
dialogShow(message:string, context:DialogContext){
this.dialogContext = context;
this.dialogMessage = message;
console.log("dialog got context ",this.dialogContext);
$(this.dialogRef.nativeElement).modal('show');
}
ComponentB 的html 是
<div #modal class="modal fade" tabindex="-1" role="dialog" id={{dialogID}}>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">CodingJedi</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" (click)="dialogHide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{dialogMessage}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="dialogHide()">Close</button>
</div>
</div>
</div>
</div>
【问题讨论】:
标签: angular6