angular表单,使用FromBuilder服务生成控件

贡烨烁
2023-12-01

Angular的FromBuilder服务为生成控件提供了方便的方法
使用:
1、导入FromBuilder服务;
2、定义一个表单模型变量:checkoutFrom;
3、在构造方法里初始化变量:

this.checkoutFrom = this.fromBuilder.group({
	name:'',
	address:''
});

4、提交表单后,要清空表单:

onSubmit(customerData){
	this.checkoutFrom.reset();
}

5、html里使用fromGroup属性绑定,把checkoutFrom绑定到模板(html文件)中的from的标签上:

<from [fromGroup] = "checkoutFrom">
	<button type = "submit">提交</button>
</from>

6、在from标签上,使用ngSubmit事件,绑定监听表单提交,并使用checkoutFrom值调用onSubmit()方法,上述代码增加为:

<from [fromGroup] = "checkoutFrom" (ngSubmit) = "onSubmit(checkoutFrom.value)">
	<button type = "submit">提交</button>
</from>

7、绑定输入框,不然类文件可不知道哪个输入框对应哪个字段。使用fromControlName属性绑定,把checkoutFrom表单控件中的name和address绑定到他们的输入字段。
完成from的代码:

<from [fromGroup] = "checkoutFrom" (ngSubmit) = "onSubmit(checkoutFrom.value)">
	<div>
		<label for = "name">
		姓名:
		</label>
		<input id = "name" type ="text" fromControlName = "name">
	</div>
	<div>
		<label for = "address">
		地址:
		</label>
		<input id = "address" type ="text" fromControlName = "address">
	</div>
	<button type = "submit">提交</button>
</from>
 类似资料: