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

时间:2018-07-31 16:59:25

标签: angular

在组件中:

 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

1 个答案:

答案 0 :(得分:0)

我将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>