![](/img/trans.png)
[英]Not able to set default values on Form Load in Angular Reactive Forms
[英]How to set default values in angular forms?
我有一个Angular应用,其中包含处理特定表单的组件。 对于其他对象内部的各种对象,此形式相对复杂。
我想知道是否可以使用初始值重置此表单。 例如:
createForm() {
this.form = this.fb.group({
id: [''],
category: ['', Validators.compose([
Validators.required,
Validators.minLength(3),
Validators.maxLength(64)
])],
user: this.fb.group({
username: ['', Validators.compose([
Validators.required,
Validators.minLength(3),
Validators.maxLength(13000)
])],
lastname: ['', Validators.compose([
Validators.required,
Validators.minLength(2),
Validators.maxLength(64)
])]
// ...and so on
当我调用form.reset()
有一个选项可以传递一个默认值,但是它似乎只对顶级属性起作用,我想为所有属性设置默认值(一个空字符串),包括在其他对象/表单组内部更深层次的对象。
有角度的本地方法吗? 谢谢
嗨,尝试将formgroup放在函数之外,然后将默认值放置如下:
this.form = this.fb.group({
id: ['sampleId'],
category: ['sampleCat', Validators.compose([
Validators.required,
Validators.minLength(3),
Validators.maxLength(64)
])],
user: this.fb.group({
username: ['sampleUsername', Validators.compose([
Validators.required,
Validators.minLength(3),
Validators.maxLength(13000)
])],
lastname: ['sampleLastname', Validators.compose([
Validators.required,
Validators.minLength(2),
Validators.maxLength(64)
])]
// ...and so on
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.