[英]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.