Javascript 以角度反应形式动态设置输入的占位符
我有这样一个组件:Javascript 以角度反应形式动态设置输入的占位符,javascript,angular,Javascript,Angular,我有这样一个组件: Form: FormGroup; constructor(private fb: FormBuilder) { } ngOnInit(): void { this.Form = this.fb.group({ contratacion: [], beneficios: this.fb.array([ this.nuevoBeneficio() ]) }); } beneficiosBase() {
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],
});
}
<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>
我的html如下所示:
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],
});
}
<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“Description”,但我想知道是否有办法做到这一点。您可以创建这样的辅助数组
listOfPlaceholder:string[]代码>然后在方法库中
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>
正确答案由Jonathat给出(您不想更改“占位符,因此不包括在FormGroup中”),只是出于好奇:[placeHolder]=“Form.get('bengiios.+i+'.descrippcion')。value”
Jonathan,您忘记了初始化变量listOfPlaceholder:string[]=[]