我有一個 mat-slide-toggle 串列,我想以反應形式使用我嘗試做這樣的事情:
HTML >>>>>>>
<form [formGroup]="notificationForm">
<div class="row">
<div class="col text-justify">
title test
</div>
</div>
<div class="notification-container mt-5">
<div class="row" *ngFor="let item of notificationsItem">
<div class="col title-notif">{{ item.title }}</div>
<div class="col">
<mat-slide-toggle
(change)="activePush()"
[formControl]="notificationForm.get(item.id)"
></mat-slide-toggle>
</div>
</div>
</div>
</form>
ts >>>>>>>>>>
export class TestComponent implements OnInit{
notificationsItem: notificationItems[] = [
{ id: 'finishedBudget', title: 'test2', selected: false },
{
id: 'zeroCampaign',
title: 'test1',
selected: false,
},
];
notificationForm = new FormGroup({
finishedBudget: new FormControl(false),
zeroCampaign: new FormControl(false),
});
private updateForm(finishedBudget: boolean, zeroCampaign: boolean) {
this.notificationForm.patchValue({
finishedBudget: finishedBudget,
zeroCampaign: zeroCampaign,
});
}
ngOnInit(){
this.updateForm(false,false)
}
}
但是當我使用這種方式時,我在 Html 檔案中得到一個錯誤: 鍵入'AbstractControl | null' 不可分配給型別 'FormControl'。型別“null”不能分配給型別“FormControl”。
我可以使用任何型別進行決議,但我不想使用任何型別
如何在不使用任何型別的情況下解決此問題?
uj5u.com熱心網友回復:
實施實際上取決于您的需求。如果您NotificationItems事先知道,我不一定會使用FormArray. 要解決您當前的問題,您可以使用formControlName而不是formControl:
<form [formGroup]="notificationForm">
<div class="row">
<div class="col text-justify">
title test
</div>
</div>
<div class="notification-container mt-5">
<div class="row" *ngFor="let item of notificationsItem">
<div class="col title-notif">{{ item.title }}</div>
<div class="col">
<mat-slide-toggle
(change)="activePush()"
[formControlName]="item.id"
></mat-slide-toggle>
</div>
</div>
</div>
</form>
這應該可以解決打字問題。
uj5u.com熱心網友回復:
嘗試這個:
在 ts 創建一些函式,如:
getFormControlById(id: string): FormControl { return this.notificationForm.get(id) as FormControl }
在 HTML 中
[formControl]="getFormControlById(item.id)"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/524411.html
標籤:有角度的角反应形式
