MST

星途 面试题库

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

在Angular里,当你创建一个自定义指令来提升应用交互性时,假设宿主元素有一个自定义属性'data - info',请描述如何在自定义指令中获取这个属性的值,并给出关键代码示例。
18.3万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 获取属性值的原理
    • 在Angular自定义指令中,可以通过ElementRef来访问宿主元素,进而获取其属性值。也可以使用@Input()装饰器来获取宿主元素上绑定的值。
  2. 使用ElementRef获取属性值
    • 首先,需要在指令类中注入ElementRef
    • 示例代码如下:
    import { Directive, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[appCustomDirective]'
    })
    export class CustomDirective {
      constructor(private el: ElementRef) {
        const dataInfoValue = this.el.nativeElement.getAttribute('data - info');
        console.log('Using ElementRef, data - info value:', dataInfoValue);
      }
    }
    
  3. 使用@Input()装饰器获取属性值
    • 在指令类中定义一个输入属性,并在宿主元素上绑定该属性。
    • 示例代码如下:
    import { Directive, Input } from '@angular/core';
    
    @Directive({
      selector: '[appCustomDirective]'
    })
    export class CustomDirective {
      @Input('data - info') dataInfoValue: string;
      constructor() {
        console.log('Using @Input, data - info value:', this.dataInfoValue);
      }
    }
    
    • 在模板中使用指令时,如下绑定:
    <div appCustomDirective data - info="some value"></div>