实现思路
- 创建自定义指令:使用Angular CLI的
ng generate directive
命令生成自定义指令。
- 监听输入框值变化:通过
@HostListener
装饰器监听输入框的input
事件,当输入值发生变化时,更新组件的数据模型。
- 监听组件数据模型变化:使用
@Input()
装饰器接收来自组件的数据模型,并通过ngOnChanges
生命周期钩子函数,当数据模型变化时,更新输入框的值。
主要代码片段
- 自定义指令代码(假设指令名为
customInput
)
import { Directive, ElementRef, HostListener, Input, OnChanges, SimpleChanges } from '@angular/core';
@Directive({
selector: '[appCustomInput]'
})
export class CustomInputDirective implements OnChanges {
@Input() appCustomInput: any;
constructor(private el: ElementRef) {}
@HostListener('input', ['$event.target.value'])
onInputChange(value: string) {
this.appCustomInput = value;
}
ngOnChanges(changes: SimpleChanges) {
if (changes['appCustomInput']) {
this.el.nativeElement.value = this.appCustomInput;
}
}
}
- 在组件模板中使用该指令
<input type="text" appCustomInput [(appCustomInput)]="componentData">
- 组件类代码
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
componentData = '';
}