绑定数据多个复选框反应形式角度4



组件内:

constructor(private prodService: productService, private fb: FormBuilder) {
this.prodService.profile()
.subscribe(
result => {
this.interested = result.category; //Get all product
this.checkReuslt = result.resultSet.interest_categroy; /// user select product
}
)
ngOnInit() {
this.formProfile = this.fb.group({
interested: this.fb.array([]),
});
}

视图中:

<div *ngFor="let data of interested">
<input type="checkbox" value="data.id" (change)="onChange(data.id, $event.target.checked)"> {{data.cat_name}}<br>
</div>

如何将数据绑定到反应形式中的复选框

In Component: 
constructor(private prodService: productService, private fb: FormBuilder) {
this.prodService.profile()
.subscribe(
result => {
this.interested = result.category; //Get all product
this.checkReuslt = result.resultSet.interest_categroy; /// user select product

}
)
ngOnInit() {
this.formProfile = this.fb.group({
interested: this.fb.array([]),
});
}
	  
In View:
<div *ngFor="let data of interested">
<input type="checkbox" value="data.id" (change)="onChange(data.id, $event.target.checked)"> {{data.cat_name}}<br>
</div>

How to bind data to the checkbox in reactive form

我将FormArrayFormGroup都添加到表单中,因为FormGroup以后可能更容易使用。

在TS中:

constructor(private prodService: productService, private fb: FormBuilder) {
this.formProfile = this.fb.group({
interested: this.fb.array([]),
interestedGroup: this.fb.group({}),
});
this.prodService.profile().subscribe(result => {
this.interested = result.category; //Get all product
this.checkResult = result.resultSet.interest_category;
const interestArr: FormArray = this.formProfile.get('interested') as FormArray;
const interestGr: FormGroup = this.formProfile.get('interestedGroup') as FormGroup;
this.interested.forEach(n => {
const initVal = this.checkResult.indexOf(n.id) > -1;
interestArr.push(this.fb.control(initVal));
interestGr.addControl(n.cat_name, this.fb.control(initVal));
});
});
}

和模板:

<form [formGroup]="formProfile">
<ng-container formGroupName="interested">
<div *ngFor="let interest of interested; let i = index;">
<input [formControlName]="i" type="checkbox">{{interest.cat_name}}
</div>
</ng-container>
<hr>
<ng-container formGroupName="interestedGroup">
<div *ngFor="let interest of interested">
<input [formControlName]="interest.cat_name" type="checkbox">{{interest.cat_name}}
</div>
</ng-container>
</form>
<pre>{{formProfile.value | json}}</pre>

最新更新