gpt4 book ai didi

forms - Angular Reactive Forms - "recursive"表单

转载 作者:行者123 更新时间:2023-12-03 21:30:19 24 4
gpt4 key购买 nike

我正在为此界面创建一个表单(例如):

interface Main {
name: string;
inners: Main[];
}

对不起命名tho:P

我想要做的是有一个表格,你可以添加额外的 Main s在旅途中,每一个内心 Main s 也可以添加自己的内部 Main s。
但我不知道如何实现 Main 的递归性s里面原来的 Main ,关于 react 形式。

我正在使用 FormBuilder ,并且正在关注 the example on the docs .

我知道这不是很多数据,但我现在的代码中没有任何非基本的东西。

最佳答案

所以,经过一番思考,我解决了这个问题!

因此,如果您按照教程进行操作,您的组件中将包含与此类似的代码:

export class HeroDetailComponent3 {
heroForm: FormGroup; // <--- heroForm is of type FormGroup

constructor(private fb: FormBuilder) { // <--- inject FormBuilder
this.createForm();
}

createForm() {
this.heroForm = this.fb.group({
name: '', // <--- the FormControl called "name"
});
}
}

所以我做了什么,我改变了 FormGroup成为 @Input() heroForm: FormGroup = null ,
我添加了一种获取 FormGroup 的方法在索引:
innerMainAt(index: number): FormGroup {
return this.inners.at(index) as FormGroup;
}

我在 html 中使用过它通过以下方式:
<div formArrayName="inners">
<div *ngFor="let inner of inners.controls; let i=index;" [formGroupName]="i">
// VVV this is the component, and it creates itself
<app-hero-form [heroForm]="innerMainAt(i)"</app-hero-form> // notice innerMainAt(i)
</div>
</div>

关于forms - Angular Reactive Forms - "recursive"表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43615537/

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