面试题答案
一键面试创建自定义属性指令基本步骤
- 创建指令类:使用
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) { }
}
- 实现指令逻辑:比如改变宿主元素的样式。
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}
- 在模块中声明指令:将创建的指令声明到对应的
NgModule
的declarations
数组中。
import { NgModule } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@NgModule({
declarations: [HighlightDirective],
exports: [HighlightDirective]
})
export class SharedModule { }
绑定和使用宿主元素属性值
- 在指令类中定义输入属性:使用
@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;
}
}
- 在宿主元素中绑定属性值:在模板中使用指令时,绑定一个值到指令的输入属性。
<p appHighlight="lightblue">This text will have a lightblue background</p>
示例代码
- 指令类代码(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;
}
}
- 模块代码(shared.module.ts)
import { NgModule } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@NgModule({
declarations: [HighlightDirective],
exports: [HighlightDirective]
})
export class SharedModule { }
- 模板代码(app.component.html)
<ng-container *ngFor="let color of ['lightgreen', 'lightpink', 'lightyellow']">
<p appHighlight="{{color}}">{{color}} background</p>
</ng-container>
- 组件类代码(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'];
}