在组件模板中获取
<button #btn (click)="onClick(btn)">按钮</button>
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
onClick(button: ElementRef<HTMLButtonElement>){
console.log(button);
}
}
在组件类中获取
<p #paragraph>段落</p>
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
@ViewChild("paragraph",{static:true})p: ElementRef<HTMLParagraphElement> | undefined;
ngAfterViewInit(){
console.log(this.p?this.p.nativeElement:undefined);
console.log(this.p?.nativeElement); // angular8不支持安全修饰符
}
}
获取一组dom元素
<ul>
<li #items>h</li>
<li #items>e</li>
<li #items>l</li>
<li #items>l</li>
<li #items>o</li>
</ul>
import { Component, QueryList, ViewChildren } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
@ViewChildren("items") li: QueryList<HTMLLIElement> | undefined;
ngAfterViewInit(){
console.log(this.li?this.li.toArray():undefined); //使用toArray获取 _results 中的dom元素
}
}
版权声明:本文为xiaozhaozai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。