MST

星途 面试题库

面试题:Angular响应式表单中如何实现双向数据绑定

在Angular响应式表单场景下,阐述实现双向数据绑定的具体步骤与相关指令,并举例说明。
26.5万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

实现双向数据绑定步骤及相关指令

  1. 引入响应式表单模块:在 app.module.ts 中导入 ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule
  ]
})
export class AppModule {}
  1. 在组件中创建表单控制对象:在组件的 .ts 文件中,从 @angular/forms 导入 FormControl
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  myControl = new FormControl('初始值');
}
  1. 在模板中使用 [(ngModel)] 指令结合响应式表单控制对象:虽然 ngModel 主要用于模板驱动表单,但在响应式表单中也能实现双向绑定效果。需要结合 formControl 指令。
<input type="text" [(ngModel)]="myControl.value" [formControl]="myControl">
<p>当前值: {{myControl.value}}</p>

这里 [(ngModel)] 负责将输入框的值与组件中 myControl.value 进行双向绑定,[formControl] 将输入框与响应式表单的 FormControl 实例关联起来。

完整示例

  1. 组件类(example.component.ts
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  myControl = new FormControl('');
}
  1. 组件模板(example.component.html
<div>
  <label for="input">输入内容:</label>
  <input type="text" id="input" [(ngModel)]="myControl.value" [formControl]="myControl">
  <p>你输入的内容是: {{myControl.value}}</p>
</div>

当在输入框中输入内容时,myControl.value 会实时更新,同时模板中显示的 myControl.value 也会同步变化,实现双向数据绑定。