面试题答案
一键面试- 指令类代码编写:
- 首先,导入必要的模块:
import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';
- 然后,创建指令类。假设指令名为
myInput
:
@Directive({
selector: '[myInput]'
})
export class MyInputDirective {
@Input() myInputModel: any;
@Output() myInputModelChange = new EventEmitter();
constructor(private el: ElementRef) {}
@HostListener('input', ['$event.target.value'])
onInputChange(value: string) {
this.myInputModel = value;
this.myInputModelChange.emit(this.myInputModel);
}
}
在上述代码中:
@Input()
装饰器定义了一个输入属性myInputModel
,用于接收来自外部的数据绑定。@Output()
装饰器定义了一个输出事件myInputModelChange
,当输入框的值发生变化时,通过这个事件将新的值传递出去。@HostListener('input', ['$event.target.value'])
监听输入框的input
事件,当输入框的值改变时,更新myInputModel
并触发myInputModelChange
事件。
- 在模板中的使用方式:
- 在组件的模板文件(例如
app.component.html
)中使用该指令:
- 在组件的模板文件(例如
<input type="text" myInput [(myInputModel)]="myValue">
<p>当前值: {{myValue}}</p>
- 在组件的 TS 文件(例如
app.component.ts
)中定义myValue
:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myValue = '';
}
这里 [(myInputModel)]
使用了 Angular 的双向数据绑定语法糖,它实际上是 [myInputModel]
输入绑定和 (myInputModelChange)
输出绑定的组合。当输入框的值改变时,myValue
会更新;同时,如果 myValue
在其他地方被修改,输入框的值也会相应更新。