javascript - 无法获取子 DOM 元素

标签 javascript html angular typescript

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

到目前为止我们尝试过什么:

最佳答案

使用嵌套组件没有简单的方法,您必须创建一个 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/

相关文章:

javascript - innerHTML 在 Chrome 中不能与 xhtml 一起正常工作

javascript - ember js 参数存在

javascript - jQuery 单击按钮时将输入中的文本附加到 div

java - 使用 Angular 和 Spring Boot 的 IntelliJ IDEA 项目

javascript - 如何将月份值从一个 Date 对象复制到另一个?

javascript - 前面有下划线但未在函数内部使用的参数的用途是什么?

javascript - JS/正则表达式 : How to set group in a regex for multiple replacement?

javascript - 尝试通过 javascript 呈现 Bootstrap 模式时未定义

javascript - 使用 php session 的事件 session 中菜单列表的方法

angular - 拒绝加载图像,因为它违反了以下内容安全策略指令(favicon)