![](/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.