Note: since the problem is a little complex, the code is abstracted for readability無法獲取子DOM元素的保持
我們一個<parent-component>
這樣的:
<child-component></child-component>
<button (click)="doSomeClick()"> Do Some Click </button>
的的<child-component>
的template
是:
<textarea #childComponentElement #someField="ngModel" name="someName" [(ngModel)]="someModel"></textarea>
我們試圖訪問這個元素在parent-component.component.ts
裏面的值如下:
export class ParentComponent implements AfterViewInit {
@ViewChild('childComponentElement') el:ElementRef;
ngAfterViewInit() {
console.log(this.el.nativeElement.value);
}
doSomeClick(){
}
}
但是它拋出這個錯誤:
我們用什麼到目前爲止已經試過:
- This gives access to
<parent-component>
, we need<textarea>
of<child-component>
- It's not about
angular-tree-component
- The directive name is camelCased
ElementRef
seems to be an old thing- This throws Cannot read property 'nativeElement' of undefined
- How is the reference between
this.element.nativeElement
&<input>
element is getting established? - There is no *ngIf or *ngSwitchCase
- There is no
*ngIf
used with#childComponentElement
- The call is inside
ngAfterViewInit
only - Time out is a very dirty approach
您是否嘗試過以下方法:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview? – Edwin
@Edwin'ngAfterViewInit'在這個用法中是正確的。只是他試圖從模板不屬於的父組件訪問templateRef。 – borislemke