0
votes

I want to add input dynamically and to specify formControlName and placeholder value for each added input

this is my view : enter image description here

when i click on "plus" i want to get this result : enter image description here

I managed to add an input each time the plus button is clicked but i couldn't specify the placeholder and formControlName value

This is my ts code :

 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: ""
    });
  }
}

this is my view :

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

This is the result that i get when i display the items enter image description here

1
Why does you div within for loop have formControlName as an input property? and placeholders are not part of reactive form controls(as far I know). - Ashish Ranjan
i want to set formControlName and placeholder value from "item.controls.placeholdername" key - Az Emna

1 Answers

1
votes

From my understanding, your form control name and placeholder value is same. Each FormGroup within the array will have one FormControl within it whose name will be dynamic. If this is true, then all we have got to do is to get the name of the form control.

I think a pipe can serve this purpose. Give it a try:

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