![](/img/trans.png)
[英]Angular: Using ViewChild and Input at the Same time, Side Effects or Best practice?
[英]Angular2. Can I use ViewChild and @Input at the same time?
我需要将一些数据传输到子元素中并在其中运行功能。 我使用ViewChild
访问该功能。 但是在孩子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
ViewChild
:
this.myModal.childParam = 'test string';
或通过功能参数发送数据:
this.myModal.modalShow('test string');
您不需要通过@ViewChild引用来设置child参数。
试试这个吧。 父模板:
<my-modal #myModal [childParam]="parentParam"></my-modal>
父组件:
private parentParam: any;
onSubmit(value: any){
this.parentParam = value;
this.myModal.modalShow();
}
parentParam的值将以这种方式直接绑定到childParam值,因此,每当更新parentParam值时,它将在子组件中可用。
如果那不起作用,则尝试将ngOnChanges添加到子组件,因为每当从父组件更新值时,您就可以调试(设置断点):
导入OnChanges(除了从@ angular / core导入的其他导入外,还添加以下内容):
import { OnChanges} from '@angular/core';
将NgOnChanges添加到您的子组件类中:
export class MyChildComponent implements OnChanges {
实现方法ngOnChanges。 只要更改输入参数,就会调用此方法:
ngOnChanges(changes: any) {
debugger; //set breakpoint
}
当this.parentParam = value;
在onSubmit()
执行,然后Angular首先需要运行更改检测以使绑定得到更新。
事件处理程序完成后,Angular运行更改检测。 在您的情况下是onSubmit()
,这意味着childParam
将在执行onSubmit()
之后获取传递的value
。
您可以做的是明确运行更改检测
constructor(private cdRef:ChangeDetectorRef) {}
onSubmit(value: any){
this.parentParam = value;
this.cdRef.detectChanges();
// here `value` is assigned to `childParam`
this.myModal.modalShow();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.