面试题答案
一键面试数据模型处理
- 响应式表单:以编程方式创建和操作,数据模型与表单控件紧密绑定,通过
FormGroup
、FormControl
等类来构建,数据变化能即时响应。例如:
import { FormGroup, FormControl } from '@angular/forms';
const myForm = new FormGroup({
username: new FormControl(''),
password: new FormControl('')
});
- 模板驱动表单:依赖模板指令来创建表单,数据模型在组件类中声明,但与表单控件的绑定相对松散。例如:
<form #myForm="ngForm">
<input type="text" name="username" ngModel>
<input type="password" name="password" ngModel>
</form>
在组件类中:
export class MyComponent {
username = '';
password = '';
}
验证方式
- 响应式表单:验证逻辑在组件类中定义,可在创建
FormControl
或FormGroup
时传入验证器函数。例如:
import { FormGroup, FormControl, Validators } from '@angular/forms';
const myForm = new FormGroup({
username: new FormControl('', [Validators.required, Validators.minLength(3)]),
password: new FormControl('', Validators.required)
});
- 模板驱动表单:验证通过模板指令添加,如
required
、minlength
等。例如:
<form #myForm="ngForm">
<input type="text" name="username" ngModel required minlength="3">
<input type="password" name="password" ngModel required>
</form>
表单创建过程
- 响应式表单:在组件类中通过代码主动创建表单结构和逻辑,更适合复杂、动态的表单场景,对表单的控制更精细。例如动态添加或移除表单控件。
// 动态添加控件
myForm.addControl('email', new FormControl(''));
- 模板驱动表单:在模板中使用Angular内置指令来声明表单和控件,语法简洁,适合简单表单场景,开发速度相对较快,但灵活性不如响应式表单。