Note: since the problem is a little complex, the code is abstracted for readability
我们有一个这样的<parent-component>
:
<child-component></child-component>
<button (click)="doSomeClick()"> Do Some Click </button>
template
的 <child-component>
为:
<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(){
}
}
但是它会抛出此错误:
Cannot read property 'nativeElement' of undefined
到目前为止我们尝试过什么:
- 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
最佳答案
使用嵌套组件没有简单的方法,您必须创建一个 EventEmitter
来发出您尝试访问的元素的 ElementRef
:
子组件.ts
class ChildComponent implements AfterViewInit {
@Output()
templateLoaded: EventEmitter<ElementRef> = new EventEmitter()
@ViewChild('childComponentElement') el: ElementRef
ngAfterViewInit(): void {
this.templateLoaded.emit(this.el)
}
}
parent.component.html
<child-component (templateLoaded)="templateLoaded($event)"
parent.component.ts
class ParentComponent {
templateLoaded(template: ElementRef): void {
// do stuff with the `template`
}
}
原始答案
尝试在ViewChild
的第二个参数中使用read
属性
@ViewChild('childComponentElement', {read: ElementRef}) el: ElementRef
如果您想知道第二个参数,这个答案给出了很好的解释:What is the read parameter in @ViewChild for
关于javascript - 无法获取子 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44303935/