如何使用Angular弹出复选框值?

时间:2019-09-24 05:20:56

标签: angular

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

add-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>

add-customer.component.ts

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

2 个答案:

答案 0 :(得分:0)

您必须使用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;
}

答案 1 :(得分:0)

add-customer-account-information.component.html

<div *ngIf="incomeSources">
        <div class="mx-3" *ngFor="let income of incomeSources.controls; let i=index">
          <mat-checkbox [formControl]="income">
            {{ localizationService.language[sourcesOfIncome[i].displayValue] }}
          </mat-checkbox>
        </div>
</div>

add-customer-account-information.component.ts

@Input() public addCustomerAccountInformationFormGroup: FormGroup;
    public get incomeSources(): any {
            if (this.addCustomerAccountInformationFormGroup) {
                return this.addCustomerAccountInformationFormGroup.get('incomeSources').value;
            }
            return null;
    }