angular - 如何使用 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,
});
解决方案
您必须使用 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;
}
推荐阅读
- c - C 调试,#if DEBUG 与 if (DEBUG)
- reactjs - 在 componentDidMount 中调用道具?
- r - R中的加权频率表
- javascript - Javascript - 以各种可能的方式组合两个数组
- node.js - WebDriverIO 和 AWS Lambda
- java - 如何在java中将eclipse控制台输出转换为txt文件
- python - 遍历文件夹和子文件夹中的所有文件并获取创建日期
- python-3.x - 在另一个 URL 中发送 URL
- macos - 如何在 Mac OS 中以 http 形式打开网站?
- c++ - std::set 是否在内存中连续存储对象?