面试题答案
一键面试- 步骤:
- 创建自定义指令。
- 在指令类的构造函数中注入
ElementRef
服务,ElementRef
提供对宿主DOM元素的引用。 - 使用
ElementRef
获取宿主元素,进而获取特定属性值。
- 关键代码:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appMyDirective]'
})
export class MyDirective {
constructor(private elementRef: ElementRef) {
const specificAttributeValue = this.elementRef.nativeElement.getAttribute('specific - attribute - name');
console.log(specificAttributeValue);
}
}
在上述代码中,通过ElementRef
的nativeElement
属性获取到宿主DOM元素,然后使用getAttribute
方法获取名为specific - attribute - name
的特定属性值。实际使用时,将specific - attribute - name
替换为真实的属性名。