首页 > 解决方案 > 如何使用 Angular 弹出复选框值?

问题描述

我是 Angular 的新手,我正在尝试找到一种方法来从表单中获取复选框值并以视图模式将其显示给用户。我尝试了一些代码,但在控制台中出现“无法读取属性 'push' 和 'toString()'”的错误。

添加-customer.component.ts

public otherIncomes = [
        { code: 1, displayValue: 'RENTAL_INCOME', selected: false },
        { code: 2, displayValue: 'PARTNERSHIP_IN_BUSINESS', selected: false},
        { code: 3, displayValue: 'INVESTMENT_PROCEEDS', selected: false },
        { code: 0, displayValue: 'OTHER', selected: false },
];

const arrIncomeSources = popupData.CustomerEntity.otherIncomeSource.toString().**split**(',');
                this.otherIncomes.forEach(element => {
                    const idx = arrIncomeSources.findIndex(x => +x === element.code);
                    this.sourcesOfOtherIncome.**push**(new FormControl(idx >= 0));
                });

add-customer-account-information.component.html

<div class="mx-3" *ngFor="let income of sourcesOfIncome" >
        <mat-checkbox formControlName="incomeSources" value="income.code">
                    {{localizationService.language[income.displayValue] }}
        </mat-checkbox>
</div>

添加-customer.component.ts

this.cusAccInfoTabFormGroup = this.formBuilder.group({
    incomeSources: this.sourcesOfOtherIncome,
 });

标签: angular

解决方案


您必须使用 formArrayName 来处理数组。

<div [formGroup]="cusAccInfoTabFormGroup">
    <div formArrayName="incomeSources">
        <div>
             <div *ngFor="let s of incomeSources.controls; let i = index" 
              [formGroupName]="i">
             here you can add your fields ....
        </div>
    </div>
</div>

在 ts 中:

get incomeSources(): FormArray{
    return this.cusAccInfoTabFormGroup.get('incomeSources') as FormArray;
}

推荐阅读