FormArray中的FormGroup

时间:2018-03-25 08:23:37

标签: angular ngfor angular4-forms formgroups

我正在使用FormArray,然后包含Form Group,但无法通过* ngFor访问html。我尝试了很多东西,但没有效果。这是打字稿代码。

  private readonly TRAINING_FORM: any = new FormGroup({
    // new FormControl('', Validators.required)
    codeSchool: new FormControl('', Validators.required),
    adressStreetInst: new FormControl('', Validators.required),
    adressCityInst: new FormControl('', Validators.required),
    adressStateInst: new FormControl('', Validators.required),
    adressZipInst: new FormControl('', Validators.required),
    phoneInst: new FormControl('', Validators.required),
    isProgramInst: new FormControl('', Validators.required),
    faxInst: new FormControl('', Validators.required),
    noteInst: new FormControl('', Validators.required),
    // trainingExtraInformation: new FormArray([])
  });


 ngOnInit() {
    this.loadForm();
  }

  loadForm() {
    const trainingArray = new FormArray([this.TRAINING_FORM]);
    const totalInst = new FormControl('', Validators.required);
    this.trainingForm = new FormGroup({
      totalInst,
      trainingArray
    });
  }

这里是html ngFor。

 <div formArrayName="trainingArray">
          <div *ngFor="let training of trainings; index as idx" formArrayName="idx">
              <div class="form-group row">
                <label class="col-sm-4 col-form-label">Training institution/hospital name
                  <span class="text-danger">*</span>
                </label>
                <div class="col-sm-8">
                  <input type="text" class="form-control" placeholder="No abbreviations, please"
                         [formControlName]="idx">
                </div>
              </div>
            </div>

2 个答案:

答案 0 :(得分:0)

我可以看到你在这里使用ngFor

<div *ngFor="let training of trainings; index as idx" formArrayName="idx">

但是你想在哪里访问/展示每个“训练”对象?模板中没有您尝试此操作的部分。

答案 1 :(得分:0)

你忘记了给FormGroup的价值!!

loadForm() {
    const trainingArray = new FormArray([this.TRAINING_FORM]);
    const totalInst = new FormControl('', Validators.required);
    this.trainingForm = new FormGroup({
      totalInst:totalInst, //<--give value to TotalInst
      trainingArray:trainingArray  //<---idem
    });
}