Search code examples
angularangular-reactive-forms

Angular How to set formcontrol in ngFor


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 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)
       }
    }

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


Solution

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

    This should solve the typing problem.