简体   繁体   中英

dynamicly set placeholder of input with angular reactive form

I have a component like this:

  Form: FormGroup;
  
  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.Form = this.fb.group({
      contratacion: [],
      beneficios: this.fb.array([ this.nuevoBeneficio() ])
    });
  }

  beneficiosBase() {
    let _form = this.Form.get('beneficios') as FormArray
    _form.push(this.nuevoBeneficio('Ejemplo: Prestaciones de ley'));
    _form.push(this.nuevoBeneficio('Ejemplo: Bono por puntualidad'));
    _form.push(this.nuevoBeneficio('Ejemplo: Prestaciones de ley'));
  }

  nuevoBeneficio(textoPlaceholder?:string): FormGroup {
    return this.fb.group({
      nombre: [],
      descripcion: [textoPlaceholder || null],
    });
  }

And my html looks like this:

     <ng-container *ngFor="let item of Form.get('beneficios').controls; let i = index;">
     <input formControlName="nombre" type="text" class="form-control" id="" [placeholder]="descripcion">
     </ng-container>

I realized this is not the way to set the placeholder value since it expects a formControlName 'descripcion', but I wonder if there's a way to do this.

You could create an auxiliary array like this listOfPlaceholder: string[]; then in your method beneficiosBase

beneficiosBase() {
  _form.push(this.nuevoBeneficio(); 
  this.listOfPlaceholders.push('Ejemplo: Prestaciones de ley');
}

Your HTML should looks like this

<ng-container *ngFor="let item of Form.get('beneficios').controls; let i = index;">
     <input formControlName="nombre" type="text" class="form-control" id="" [placeholder]="listOfPlaceholders[i]">
</ng-container>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM