面试题答案
一键面试实现思路
- 在指令中使用
ngModel
来处理双向数据绑定。ngModel
是Angular提供的用于双向数据绑定的指令,它内部处理了视图到模型和模型到视图的同步。 - 通过
@Input()
装饰器接收来自组件的属性值,并将其绑定到输入框。 - 监听输入框的
input
事件,当输入值变化时,更新组件的属性值。
核心代码
- 创建自定义指令
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appMyTwoWayBinding]'
})
export class MyTwoWayBindingDirective {
@Input('appMyTwoWayBinding') value: any;
constructor(private el: ElementRef) {}
@HostListener('input', ['$event.target.value'])
onInput(value: string) {
this.value = value;
}
}
- 在组件模板中使用指令
<input type="text" appMyTwoWayBinding [(appMyTwoWayBinding)]="componentProperty">
- 在组件类中定义属性
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html'
})
export class MyComponent {
componentProperty = '';
}
以上代码实现了在Angular中自定义指令的双向数据绑定功能,当输入框值改变时更新组件属性,组件属性改变时也更新输入框值。实际应用中可根据需求对指令和组件进一步完善。