我需要将一些数据传输到子元素中并在其中运行函数。
我使用 ViewChild
来访问函数。但是在 child childParam
中仍然未定义。
父模板:
<my-modal #myModal [childParam]="parentParam"></my-modal>
父组件:
@ViewChild('myModal') myModal;
parentParam: any;
onSubmit(value: any){
this.parentParam = value;
this.myModal.modalShow();
}
子组件:
@Input() childParam: any;
modalShow(){
console.log(this.childParam);
}
为什么 childParam
是未定义的?
更好的是:ViewChild
直接改变childParam
:
this.myModal.childParam = 'test string';
或者通过函数参数发送数据:
this.myModal.modalShow('test string');
最佳答案
当 this.parentParam = value;
在 onSubmit()
中执行时,Angular 首先需要运行更改检测以更新绑定(bind)。
Angular 在事件处理程序完成时运行更改检测。在你的情况下是 onSubmit()
这意味着 childParam
将获得 value
after onSubmit ()
被执行了。
你可以做的是明确地运行变化检测
constructor(private cdRef:ChangeDetectorRef) {}
onSubmit(value: any){
this.parentParam = value;
this.cdRef.detectChanges();
// here `value` is assigned to `childParam`
this.myModal.modalShow();
}
关于 Angular 2。我可以同时使用 ViewChild 和 @Input 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274276/