Home > Net >  Angular How to set formcontrol in ngFor
Angular How to set formcontrol in ngFor

Time:11-01

I have a list of mat-slide-toggle that I want to use in reactive form I try to do something like this:

HTML>>>>>>>

 <form [formGroup]="notificationForm">
        <div >
          <div >
            title test
          </div>
        </div>
        <div >
          <div  *ngFor="let item of notificationsItem">
            <div >{{ item.title }}</div>
            <div >
              <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)
       }
    }

but when I use this way I get an error in the Html file: Type 'AbstractControl | null' is not assignable to type 'FormControl'. Type 'null' is not assignable to type 'FormControl'.

I can use type any for resolve but I don't want to use any

How can I resolve this problem without using the type any??

CodePudding user response:

The implementation really depends on your needs. If you know the NotificationItems in advance I wouldn't necessarily go for an implementation with FormArray. To solve your current problem you can just use formControlName instead of formControl:

 <form [formGroup]="notificationForm">
        <div >
          <div >
            title test
          </div>
        </div>
        <div >
          <div  *ngFor="let item of notificationsItem">
            <div >{{ item.title }}</div>
            <div >
              <mat-slide-toggle
                (change)="activePush()"
                [formControlName]="item.id"
              ></mat-slide-toggle>
            </div>
          </div>
        </div>
 </form>

This should solve the typing problem.

CodePudding user response:

Try this:

  1. In ts create some function like:

    getFormControlById(id: string): FormControl { return this.notificationForm.get(id) as FormControl }

  2. In HTML

[formControl]="getFormControlById(item.id)"

  • Related