如何在 html 模板中打印 formControlName 值
How to print formControlName value in html template
我想在 HTML 模板中打印 fontControlName 的值 我尝试了不同的方法,但没有任何效果。下面的代码工作正常,值打印在输入中。
Angular 版本 12
HTML
<div formArrayName="billings" *ngFor="let bill of billings.controls; let i = index;">
<div [formGroupName]="i">
<div>
<tr>
<td>
{{bill.get('heads')}} print object object
{{bill.get('heads').value}} <-- possible null compile time error-->
<input class="form-control" type="text" formControlName="heads">
</td>
<td>
<input class="form-control" type="number" step=".01" formControlName="amount">
</td>
</tr>
</div>
</div>
</div>
</form>
Component
constructor(private fb: FormBuilder, private transactionService: TransactionService) {
this.maintenanceForm = this.fb.group({
billings: this.fb.array([])
})
}
setExistingMaintenance(billings: IRegularMaintenaceI[]): FormArray {
const formArray = new FormArray([]);
billings.forEach(bill => {
formArray.push(this.fb.group({
heads: bill.accountHeads.heads,
amount: bill.amount
}))
});
return formArray;
}```
[Solution but not working for me][1]:
在您的 ts 文件中添加方法以获取控件
getControlByName(groupIndex: number, controlName: string): FormControl{
const fg = this.billings.at(groupIndex) as FormGroup;
return fg.get(controlName) as FormControl;
}
和模板中的{{ getControlByName(i, 'heads').value }}
取值,使用group-index和control-name检索formControl
.
<div [formGroupName]="i">
..
{{ getControlByName(i, 'heads').value }}
<input class="form-control" type="text" formControlName="heads">
..
我想在 HTML 模板中打印 fontControlName 的值 我尝试了不同的方法,但没有任何效果。下面的代码工作正常,值打印在输入中。
Angular 版本 12
HTML
<div formArrayName="billings" *ngFor="let bill of billings.controls; let i = index;">
<div [formGroupName]="i">
<div>
<tr>
<td>
{{bill.get('heads')}} print object object
{{bill.get('heads').value}} <-- possible null compile time error-->
<input class="form-control" type="text" formControlName="heads">
</td>
<td>
<input class="form-control" type="number" step=".01" formControlName="amount">
</td>
</tr>
</div>
</div>
</div>
</form>
Component
constructor(private fb: FormBuilder, private transactionService: TransactionService) {
this.maintenanceForm = this.fb.group({
billings: this.fb.array([])
})
}
setExistingMaintenance(billings: IRegularMaintenaceI[]): FormArray {
const formArray = new FormArray([]);
billings.forEach(bill => {
formArray.push(this.fb.group({
heads: bill.accountHeads.heads,
amount: bill.amount
}))
});
return formArray;
}```
[Solution but not working for me][1]:
在您的 ts 文件中添加方法以获取控件
getControlByName(groupIndex: number, controlName: string): FormControl{
const fg = this.billings.at(groupIndex) as FormGroup;
return fg.get(controlName) as FormControl;
}
和模板中的{{ getControlByName(i, 'heads').value }}
取值,使用group-index和control-name检索formControl
.
<div [formGroupName]="i">
..
{{ getControlByName(i, 'heads').value }}
<input class="form-control" type="text" formControlName="heads">
..