[英]dynamicly set placeholder of input with angular reactive form
我有一个这样的组件:
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],
});
}
我的 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>
我意识到这不是设置占位符值的方法,因为它需要一个 formControlName 'descripcion',但我想知道是否有办法做到这一点。
你可以创建一个像这样的辅助数组listOfPlaceholder: string[];
然后在你的方法中 beneficiosBase
beneficiosBase() {
_form.push(this.nuevoBeneficio();
this.listOfPlaceholders.push('Ejemplo: Prestaciones de ley');
}
你的 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.