MST

星途 面试题库

面试题:Angular自定义指令之基本结构与属性绑定

请简述在Angular中创建一个自定义属性指令的基本步骤。并且说明如何在指令中绑定和使用来自宿主元素的属性值。请给出一个简单的示例代码来展示这一过程。
27.3万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

创建自定义属性指令基本步骤

  1. 创建指令类:使用ng generate directive命令生成一个指令类,或者手动创建一个继承自Directive的类。例如:
import { Directive } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor() { }
}

这里selector指定了指令在模板中使用的属性名,appHighlight为自定义的名称。 2. 注入依赖(可选):如果指令需要访问一些服务,比如ElementRef来操作宿主元素,可在构造函数中注入。例如:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }
}
  1. 实现指令逻辑:比如改变宿主元素的样式。
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }
}
  1. 在模块中声明指令:将创建的指令声明到对应的NgModuledeclarations数组中。
import { NgModule } from '@angular/core';
import { HighlightDirective } from './highlight.directive';

@NgModule({
  declarations: [HighlightDirective],
  exports: [HighlightDirective]
})
export class SharedModule { }

绑定和使用宿主元素属性值

  1. 在指令类中定义输入属性:使用@Input()装饰器来定义一个输入属性,用于接收宿主元素传递过来的值。
import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input() appHighlight: string;

  constructor(private el: ElementRef) { }

  ngOnInit() {
    this.el.nativeElement.style.backgroundColor = this.appHighlight;
  }
}
  1. 在宿主元素中绑定属性值:在模板中使用指令时,绑定一个值到指令的输入属性。
<p appHighlight="lightblue">This text will have a lightblue background</p>

示例代码

  1. 指令类代码(highlight.directive.ts)
import { Directive, ElementRef, Input, OnInit } 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;
  }
}
  1. 模块代码(shared.module.ts)
import { NgModule } from '@angular/core';
import { HighlightDirective } from './highlight.directive';

@NgModule({
  declarations: [HighlightDirective],
  exports: [HighlightDirective]
})
export class SharedModule { }
  1. 模板代码(app.component.html)
<ng-container *ngFor="let color of ['lightgreen', 'lightpink', 'lightyellow']">
  <p appHighlight="{{color}}">{{color}} background</p>
</ng-container>
  1. 组件类代码(app.component.ts)
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  colors = ['lightgreen', 'lightpink', 'lightyellow'];
}