gpt4 book ai didi

angular - 具有验证功能的表单(嵌入式组件)中可重用的嵌套子组件

转载 作者:行者123 更新时间:2023-12-02 02:54:41 25 4
gpt4 key购买 nike

假设我们有一个地址并希望以多种形式重复使用它(例如个人、公司...)在 Angular 中,一切都是组件,因此我们可能应该编写一个组件。

最好的方法是什么?事实证明,这并不容易。它应该封装数据并验证嵌入的表单字段。我找到了两个解决问题的方法:

<强>1。自定义表单组件

我不喜欢它的地方:过于复杂,所有内容都在子组件内委托(delegate)。通过验证,您将需要某种“内部表单”才能使验证工作。表单控件必须在父级中定义,封装是不可能的。简单例子,见: https://stackblitz.com/edit/angular-nested-form-custum-component-test

<强>2。组件,有两个输入:FormGroup 和 form-submitted-state

想法取自 https://medium.com/spektrakel-blog/angular2-building-nested-reactive-forms-7978ecd145e4

比自定义表单组件简单得多。我们需要提供在嵌套组件之外构建的 FormGroup。如果我们想在“onSubmit”中显示验证错误,我们还需要向子组件提供表单的“已提交状态”。简单的例子,见 https://stackblitz.com/edit/angular-nested-formcomponent-test

对解决问题有什么意见或更好的想法吗?

最佳答案

Demo

您可以通过将 FormGroup 传递给具有初始值的嵌套控件并允许嵌套控件定义其自己的内部表单组以及任何验证器来支持封装。

app.component.html

<nested-form-cmp 
init="foo"
[formSubmitted]="f.submitted"
[grp]="myForm">
</nested-form-cmp>

AppComponent 只需要初始化它自己的表单数据:

export class AppComponent  {

myForm: FormGroup;

constructor(private fb: FormBuilder) {
this.myForm = fb.group({
name: ['', Validators.required]
})
}

submit(form: NgForm) {
console.log("Reactive Form submitted: " + form.submitted);
}
}

nested-form.component.html

嵌套组件将负责创建自己的嵌套 FormGroup,并使用验证器对其进行初始化:

<div [formGroup]="grp">
<div formGroupName="innerGrp">
<label>
Inner name:
<input formControlName="name2" type="text" id="outer"/>
</label>
<span class="error" *ngIf="(formSubmitted || grp.get('innerGrp.name2').touched) && grp.get('innerGrp.name2').hasError('required')">
Inner name is required
</span>
</div>
</div>

nested-form.component.ts

export class NestedFormComponent implements OnInit{

// The FormGroup built in the parent
@Input() public grp: FormGroup;
@Input() public init: string;

// Needed, because the FormGroup does not get the forms submitted state
@Input() public formSubmitted: boolean;
constructor(private fb: FormBuilder){

}

ngOnInit() {
this.grp.setControl('innerGrp', this.fb.group({
name2: [this.init, Validators.required]
}))
}
}

关于angular - 具有验证功能的表单(嵌入式组件)中可重用的嵌套子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50115611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com