简体   繁体   English

使用角反应形式动态设置输入的占位符

[英]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:我的 html 看起来像这样:

     <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.我意识到这不是设置占位符值的方法,因为它需要一个 formControlName 'descripcion',但我想知道是否有办法做到这一点。

You could create an auxiliary array like this listOfPlaceholder: string[];你可以创建一个像这样的辅助数组listOfPlaceholder: string[]; then in your method beneficiosBase然后在你的方法中 beneficiosBase

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

Your HTML should looks like this你的 HTML 应该是这样的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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