MST

星途 面试题库

面试题:Angular自定义指令中如何获取宿主元素的属性

在Angular中进行自定义指令开发时,要求写出获取宿主元素上某个特定属性值的代码实现步骤及关键代码。
17.3万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 步骤
    • 创建自定义指令。
    • 在指令类的构造函数中注入ElementRef服务,ElementRef提供对宿主DOM元素的引用。
    • 使用ElementRef获取宿主元素,进而获取特定属性值。
  2. 关键代码
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);
  }
}

在上述代码中,通过ElementRefnativeElement属性获取到宿主DOM元素,然后使用getAttribute方法获取名为specific - attribute - name的特定属性值。实际使用时,将specific - attribute - name替换为真实的属性名。