MST

星途 面试题库

面试题:Angular 中自定义指令的基本结构与使用场景

请简述在 Angular 中创建一个自定义指令的基本结构,包括所需的装饰器和必要的方法。并举例说明至少两种适合使用自定义指令的开发场景。
38.0万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

创建自定义指令基本结构

  1. 装饰器:使用 @Directive 装饰器来标识一个类为指令。它接收一个元数据对象作为参数,其中 selector 用于指定指令在模板中的选择器。
    import { Directive } from '@angular/core';
    
    @Directive({
      selector: '[appMyDirective]'
    })
    export class MyDirective {
      constructor() {}
    }
    
  2. 必要的方法
    • 生命周期钩子方法
      • ngOnInit:在指令初始化后调用,常用于初始化指令相关的操作,比如获取元素引用、订阅服务等。
      import { Directive, OnInit } from '@angular/core';
      
      @Directive({
        selector: '[appMyDirective]'
      })
      export class MyDirective implements OnInit {
        constructor() {}
      
        ngOnInit() {
          // 初始化操作
        }
      }
      
      • ngOnDestroy:在指令销毁时调用,用于清理资源,比如取消订阅的 Observable 等。
      import { Directive, OnInit, OnDestroy } from '@angular/core';
      import { Subscription } from 'rxjs';
      
      @Directive({
        selector: '[appMyDirective]'
      })
      export class MyDirective implements OnInit, OnDestroy {
        private mySubscription: Subscription;
        constructor() {}
      
        ngOnInit() {
          this.mySubscription = // 订阅某个 Observable
        }
      
        ngOnDestroy() {
          this.mySubscription.unsubscribe();
        }
      }
      

适合使用自定义指令的开发场景

  1. 元素样式控制:比如创建一个指令来根据某个条件动态改变元素的背景颜色。
    • 指令代码
    import { Directive, Input, OnInit, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[appHighlight]'
    })
    export class HighlightDirective implements OnInit {
      @Input() appHighlight: string;
    
      constructor(private el: ElementRef) {}
    
      ngOnInit() {
        this.el.nativeElement.style.backgroundColor = this.appHighlight;
      }
    }
    
    • 模板使用
    <div appHighlight="yellow">This div will have yellow background</div>
    
  2. 表单验证增强:创建一个自定义指令用于验证输入框的值是否符合特定格式,比如只能输入数字。
    • 指令代码
    import { Directive, Input, OnInit, Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
    
    @Directive({
      selector: '[appNumberOnly]',
      providers: [
        { provide: NG_VALIDATORS, useExisting: NumberOnlyDirective, multi: true }
      ]
    })
    export class NumberOnlyDirective implements OnInit, Validator {
      constructor() {}
    
      ngOnInit() {}
    
      validate(control: AbstractControl): { [key: string]: any } | null {
        const isValid = /^\d+$/.test(control.value);
        return isValid? null : { 'numberOnly': true };
      }
    }
    
    • 模板使用
    <input type="text" appNumberOnly [(ngModel)]="numberValue" name="numberInput">