响应式表单的动态表单问题

时间:2019-06-23 10:18:46

标签: html angular

我想在按钮按下时创建一个动态输入字段,并且可以通过反应形式在按钮按下时成功创建一个新的输入字段,但是现在我想根据API数据在输入字段中设置预定义的值。就像从API中获取6个名称一样,我想在Init上创建6个输入字段,然后想在按下按钮时新建输入字段。这是我尝试的代码,我可以创建新的输入字段,但无法根据Init上的API数据创建输入字段。

Component.ts

export class ScreenmodalComponent implements OnInit {

  @Input() screendetails;
  personalForm : FormGroup;
  arrayItems: any = [];
  screenList: string;

  constructor(private activeModal: NgbActiveModal, private formbuilder: FormBuilder, private pagesService: PagesService, private utilService: UtilService) { }

  ngOnInit() {
    this.personalForm = this.formbuilder.group({
      other: this.formbuilder.array([ this.addanotherForm()])
    });
    // Api call
    this.pagesService.GetScreens('').then(res => {
      console.log('get screens api', res);
      for (let i = 0; i < res['data']['length']; i++) {
        this.arrayItems = res['data'][i]['name'] //names which I want to set as input field value and generate input fields for every name
      }
    }).catch(error => {
    this.utilService.showError('Something went wrong', 'Error');
    console.log('err is', error);
    });
  }


  addanother():void {
    (<FormArray>this.personalForm.get('other')).push(this.addanotherForm());
  }
  addanotherForm(): FormGroup{
 return this.formbuilder.group({
      screenname: [''],
    });
  }

clear(i : number){    
  (<FormArray>this.personalForm.get('other')).removeAt(i);
}

onSubmit(): void {

  console.log(this.personalForm.value);
}

closeModel() {
    this.activeModal.close();
  }
}

Componenent.html代码

<div class="custom_modal pb-3">
    <div class="modal-header border-0 p-1 pl-3 pr-3 d-flex justify-content-between align-items-center">
      <h3 class="m-0">Project: {{screendetails.name}}</h3>
      <button type="button" class="close" data-dismiss="modal" (click)="closeModel()">&times;</button>
    </div>

    <div class="modal-body p-3">
      <div class="body_top d-flex justify-content-between mb-4 mt-2 align-items-center">
        <h3 class="title m-0">Add Screens</h3>
      </div>
      <form [formGroup]="personalForm" (ngSubmit)="onSubmit()">
      <div formArrayName="other" class="form-group" *ngFor="let other of personalForm.get('other').controls; let i = index" >
        <div [formGroupName] = "i">
      <div class="screen_row mb-4">
        <div class="row">
          <div class="col-md-3 col-sm-3 d-flex align-items-center">
            <label>Screen Name</label>
          </div>
          <div class="col-md-8 col-sm-8 pl-0 pl-sm-3">
              <input type="text" class="form-control rounded-0" formControlName="screenname" name="screenname">
          </div>
          <div class="col-md-1 col-sm-1 d-flex align-items-center justify-content-center pl-0 pl-sm-3">
              <button type="button" class="close" (click)="clear(i)">&times;</button>
          </div>
        </div>
      </div>
    </div>
    </div>

    <div class="modal-footer border-0 d-table w-100">
        <button type="button" class="btn-primary float-left" (click)="addanother()">Add New Screen</button>
        <div class="float-right">
          <button type="button" class="btn-primary mr-3" data-dismiss="modal" (click)="onSubmit();">Apply</button>
          <button type="button" class="btn-primary cancle" data-dismiss="modal" (click)="closeModel()">Cancel</button>
        </div>
    </div>
  </form>
</div>
  </div>

这是我的代码。默认情况下,请帮助我根据API调用中的名称数设置输入字段。谢谢

1 个答案:

答案 0 :(得分:0)

通常,您更改函数addAnotherForm以允许传递数据

addanotherForm(data:any): FormGroup{
 return this.formbuilder.group({
      screenname: [data],
    });
  }

根据您的情况,您必须更改函数addanother

addanother(data:any):void {
    (<FormArray>this.personalForm.get('other')).push(this.addanotherForm(data));
  }

因此,您的ngOnInit可能像这样。

//at first an Empty FormArray
this.personalForm = this.formbuilder.group({
      other: this.formbuilder.array([])
    });
    // Api call
    this.pagesService.GetScreens('').then(res => {
      console.log('get screens api', res);
      for (let i = 0; i < res['data']['length']; i++) {
        this.arrayItems = res['data'][i]['name'] 
        this.addanother(res['data'][i]['name'] //fill the array
      }
    }).catch(error => {
    this.utilService.showError('Something went wrong', 'Error');
    console.log('err is', error);
    });

好吧,实际上,您只需输入所有代码即可-实际上,您不需要this.arrayItems-,我们使用地图

this.pagesService.GetScreens('').then(res => {
  this.personalForm=new FormGroup({
       other:new FormArray(
           res['data'].map(d>=>{
             return new FormGroup({
                screenname:new FormControl(d.name))
             })
           })
       )
  })
}).catch(error => {
    this.utilService.showError('Something went wrong', 'Error');
    console.log('err is', error);
});

注意:如果只想控制FormArray,则无需创建ForGroup,并且formArray只能是formControls的formArray,而不能是FormGroup的FormArray。