设置添加的动态输入的参数

问题描述 投票:0回答:1

我想动态添加输入并为每个添加的输入指定formControlName和占位符值

这是我的观点:enter image description here

当我点击“加号”我想得到这个结果:enter image description here

每次单击加号按钮时我都设法添加输入,但我无法指定占位符和formControlName值

这是我的代码:

 addLink() { 
 //when the plus button is clicked

   const placeholdervalue = this.addForm.get("placeholdervalue").value;
   this.items = this.addForm.get("items") as FormArray;
    this.items.push(this.createItem(placeholdervalue));
    console.log(this.addForm.get("items"));
  }

  createItem(placeholdervalue: string): FormGroup {
    let a = { [placeholdervalue]: "" };
    return this.formBuilder.group(a);
  }
  ngOnInit() {
    this.addForm = this.formBuilder.group({
      items: this.formBuilder.array([]),
      placeholdervalue: ""
    });
  }
}

这是我的看法:

<div class="row">
            <div
              class="col-md-3"
              formArrayName="items"
              *ngFor="
                let item of addForm.get('items').controls;
                let i = index
              "
            >
              <div [formGroupName]="i">
                <mat-form-field class="example-full-width">
                  <input
                    matInput
                    formControlName="" // i want to retrieve it from item
                    placeholder="" 
                  />
                </mat-form-field>
              </div>
            </div>
          </div>

这是我在显示enter image description here项目时得到的结果

angular typescript angular-reactive-forms
1个回答
1
投票

根据我的理解,您的表单控件名称和占位符值是相同的。数组中的每个FormGroup都有一个FormControl,其名称将是动态的。如果这是真的,那么我们所要做的就是获取表单控件的名称。

我认为管道可以达到这个目的。试试看:

@Pipe({
  name: 'getFormControlName'
})
export class GetFormControlNamePipe implements PipeTransform {

  transform(value: FormGroup): string {
    return Object.keys(value.controls)[0]
  }

}


<div [formGroupName]="i">
  <mat-form-field class="example-full-width">
    <input
      matInput
      formControlName="{{item | getFormControlName}}"
      placeholder="{{item | getFormControlName}}" 
    />
  </mat-form-field>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.