【发布时间】:2017-06-01 09:38:53
【问题描述】:
注意:由于问题有点复杂,为了便于阅读,对代码进行了抽象
我们有一个这样的<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(){
}
}
但是它会抛出这个错误:
无法读取未定义的属性“nativeElement”
到目前为止我们尝试了什么:
- This gives access to
<parent-component>, we need<textarea>of<child-component> - It's not about
angular-tree-component - The directive name is camelCased
ElementRefseems 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
*ngIfused with#childComponentElement - The call is inside
ngAfterViewInitonly - Time out is a very dirty approach
【问题讨论】:
-
你试过这里的方法吗:angular.io/docs/ts/latest/guide/…?
-
@Edwin
ngAfterViewInit在这种用法中是正确的。只是他试图从一个模板不属于的父组件访问templateRef。
标签: javascript html angular typescript