Angular2。我可以同时使用ViewChild和@Input吗?
问题描述:
我需要将一些数据转移到子元素并在其中运行函数。 我使用ViewChild
来访问该功能。但在孩子childParam
仍未定义。Angular2。我可以同时使用ViewChild和@Input吗?
父模板:
<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
是不确定的?
更好的是:改变直接childParam
通过ViewChild
:
this.myModal.childParam = 'test string';
或发送数据,通过功能参数:
this.myModal.modalShow('test string');
答
当this.parentParam = value;
在onSubmit()
然后角首先需要执行运行变化检测绑定得到更新。
当事件处理程序完成时,角度运行会更改检测。在你的情况是onSubmit()
这意味着childParam
将得到value
通过之后onSubmit()
被执行。
你可以做的是运行变化检测明确地
constructor(private cdRef:ChangeDetectorRef) {}
onSubmit(value: any){
this.parentParam = value;
this.cdRef.detectChanges();
// here `value` is assigned to `childParam`
this.myModal.modalShow();
}
答
你并不需要通过@ViewChild基准来设定参数孩子。
试试这个。父模板:
<my-modal #myModal [childParam]="parentParam"></my-modal>
父组件:
private parentParam: any;
onSubmit(value: any){
this.parentParam = value;
this.myModal.modalShow();
}
parentParam的值将绑定到childParam值直接以这种方式使每当parentParam值更新它会在子组件可用。
如果不工作,那么尝试添加ngOnChanges到子组件,因为你会再能调试(设置断点)每当值从父更新:
进口OnChanges(添加此除了等进口从@角/核心)有:
import { OnChanges} from '@angular/core';
添加NgOnChanges你的孩子组件类:
export class MyChildComponent implements OnChanges {
Implemen t方法ngOnChanges。每当输入参数发生变化,该方法将被调用:
ngOnChanges(changes: any) {
debugger; //set breakpoint
}
我想'parentParam'尚未设置时'modalShow()'被调用,但很难说,因为代码不允许派生出可能会发生的事情。 –
我创建了plunker [链接](https://plnkr.co/edit/ZcZaJ0Wbu9CAobxkd2LJ?p=preview)。当我第一次点击按钮 - 没有显示任何内容时,第二次点击 - 显示字符串。 – MikeS