【发布时间】:2020-10-31 21:07:17
【问题描述】:
我有一个包含输入标签的子组件,我需要在父组件中设置 formControlName,但出现错误
child.html
<form [formGroup]="formGroupName">
<div class="input">
<input type="text" [formControlName]="formControlName" />
<span class="label">{{ label }}</span>
</div>
</form>
child.ts
export class FactorComponent implements OnInit {
@Input("label") label: string;
@Input("formControlName") formControlName: string;
@Input("formGroupName") formGroupName: string;
constructor() {}
ngOnInit() {}
}
parent.html
<form [formGroup]="form" (ngSubmit)="onCalcute()">
<div class="child" >
<div class="estimate-part">
<ng-container *ngFor="let factor of allFactors">
<otk-factor
[label]="factor?.label"
[formControlName]="factor?.id"
[formGroupName]="form"
></otk-factor>
</ng-container>
</div>
</div>
<div class="btn-row">
<button class="calcute" type="submit">estimate</button>
</div>
</form>
parent.ts
export class GamificationComponent implements OnInit {
@Input("rooms") rooms: HostRoomInfoModel;
@Input("roomSelected") roomSelected;
@Input("roomId") roomId: number;
showCalcuteBorder: boolean = false;
form: FormGroup;
allFactors = [
{
id: "price",
label: "تومان",
selected: false
},
{
id: "discount",
label: "درصد",
selected: false
},
{
id: "response",
label: "درخواست",
selected: false
},
{
id: "viewCount",
label: "رزرو",
selected: false
},
{
id: "acceptance",
label: "نفر",
selected: false
}
];
constructor(private estimationService: EstimationService) {
this.form = new FormGroup({
price: new FormControl(null),
discount: new FormControl(null),
response: new FormControl(null),
viewCount: new FormControl(null),
acceptance: new FormControl(null)
});
}
ngOnInit(): void {}
onCalcute() {
this.showCalcuteBorder = true;
console.log(this.form.value);
}
得到这个错误也得到了表单值 enter image description here
实际上我使用响应式表单,我想将输入标签用作子组件,但似乎无法从父组件中找到它们的值
【问题讨论】:
-
formControlName不幸的是,您不能通过数据绑定输入将其转发给子组件。完成这项工作的唯一方法是将FactorComponent转换为自定义表单控件。
标签: angular typescript angular-reactive-forms