面试题答案
一键面试实现双向数据绑定步骤及相关指令
- 引入响应式表单模块:在
app.module.ts
中导入ReactiveFormsModule
。
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule
]
})
export class AppModule {}
- 在组件中创建表单控制对象:在组件的
.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('初始值');
}
- 在模板中使用
[(ngModel)]
指令结合响应式表单控制对象:虽然ngModel
主要用于模板驱动表单,但在响应式表单中也能实现双向绑定效果。需要结合formControl
指令。
<input type="text" [(ngModel)]="myControl.value" [formControl]="myControl">
<p>当前值: {{myControl.value}}</p>
这里 [(ngModel)]
负责将输入框的值与组件中 myControl.value
进行双向绑定,[formControl]
将输入框与响应式表单的 FormControl
实例关联起来。
完整示例
- 组件类(
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('');
}
- 组件模板(
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
也会同步变化,实现双向数据绑定。