2017-04-25 108 views
2

我创建形式为这个接口(例如):角活性形式 - “递归”的形式

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

遗憾的命名寿:P

我想要做的有一种形式,您可以在旅途中添加其他Main s,并且每个内部Main s也可以添加自己的内部Main s。
但我不知道如何在原始Main内部实现关于反应形式的Main的递归性。

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

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

回答

0

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

所以,如果你按照教程,你就会有类似下面的代码在你的组件:

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
我也加

innerMainAt(index: number): FormGroup { 
    return this.inners.at(index) as FormGroup; 
} 

,我已经通过以下方式使用它在html:用于获取FormGroup索引的方法

<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>