[英]Parent to Child communication not working as expected
我有两个组件,一个父母和一个孩子。 每次我单击父组件中的某个按钮时,都会填充一个 object 并通过@Input
装饰器发送到子组件。
这里的问题是,即使在子组件中检测到 object 的更改,我尝试填充的数据也只会出现在偶数点击中。
这是我的代码目前的样子:
父组件.ts
private toSend = {};
public sendToChild() {
var objectToSend = {
headerMessage:`Title`,
bodyMessage:"Body"
};
this.toSend = { ...objectToSend };
$('#childComponent').appendTo("body").modal('toggle');
}
父组件.html
<child-component #childComponent [data]="toSend">
</child-component>
child.component.ts
public headerMessage: string = "";
public bodyMessage: string = "";
@Input('data')
set data(data: any) {
if (data !== undefined && data.length !== 0) {
this.setData(data);
}
}
private setData(el): void {
for (let key in el) {
switch (key) {
case "headerMessage":
this.headerMessage = el[key];
break;
case "bodyMessage":
this.bodyMessage = el[key];
break;
}
}
}
child.component.html
<div class="modal" tabindex="-1" role="dialog" id="childComponent">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header" style="padding: 1rem;">
<h5 class="modal-title">{{headerMessage}}</h5>
<button type="button" class="close" id="btn-close-id" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal-body-id">
<div class="container-fluid">
<div class="col-12">
{{bodyMessage}}
</div>
</div>
</div>
<div class="modal-footer" style="padding: 1rem;">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
我也尝试使用ngOnChanges
,我能够打印我每次发送的 object,但我遇到了同样的问题。
您可以使用ChangeDetectorRef
强制检测
import { ..., ChangeDetectorRef } from '@angular/core';
将其添加到您的构造函数中
constructor(private _cdr: ChangeDetectorRef) {...}
在你的子组件中
this._cdr.markForCheck();
// or if not working
this._cdr.detectChanges()
另一件事,JQuery 不推荐与 Angular 一起使用。 如果你想在你的项目中使用模态,你应该检查Angular 材料模态或制作你自己的模态组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.