MST

星途 面试题库

面试题:Angular自定义指令实现双向数据绑定

在Angular应用交互性提升场景下,要求通过自定义指令实现双向数据绑定。例如,在一个自定义的文本输入指令中,输入框的值变化能实时更新到组件的数据模型,同时组件数据模型的变化也能实时反映在输入框上。请阐述实现思路并给出主要代码片段。
30.0万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建自定义指令:使用Angular CLI的ng generate directive命令生成自定义指令。
  2. 监听输入框值变化:通过@HostListener装饰器监听输入框的input事件,当输入值发生变化时,更新组件的数据模型。
  3. 监听组件数据模型变化:使用@Input()装饰器接收来自组件的数据模型,并通过ngOnChanges生命周期钩子函数,当数据模型变化时,更新输入框的值。

主要代码片段

  1. 自定义指令代码(假设指令名为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;
    }
  }
}
  1. 在组件模板中使用该指令
<input type="text" appCustomInput [(appCustomInput)]="componentData">
  1. 组件类代码
import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  componentData = '';
}