有人知道如何获取组件模板中定义的元素吗?聚合物让$和$$变得很容易。
我只是想知道如何在Angular中实现它。
以教程中的例子为例:
import {Component} from '@angular/core';
@Component({
selector:'display',
template:`
<input #myname (input)="updateName(myname.value)"/>
<p>My name : {{myName}}</p>
`
})
export class DisplayComponent {
myName: string = "Aman";
updateName(input: String) {
this.myName = input;
}
}
我如何从类定义中捕获或获得p或输入元素的引用?
快速使用的最小示例:
import { Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'my-app',
template:
`
<input #inputEl value="hithere">
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('inputEl') inputEl:ElementRef;
ngAfterViewInit() {
console.log(this.inputEl);
}
}
在感兴趣的DOM元素上放置一个模板引用变量。在我们的例子中,这是<input>标签上的#inputEl。
在组件类中,通过@ViewChild装饰器注入DOM元素
访问ngAfterViewInit生命周期钩子中的元素。
注意:
如果你想操作DOM元素,请使用Renderer2 API而不是直接访问元素。允许直接访问DOM会使应用程序更容易受到XSS攻击