mercredi 16 juin 2021

Angular Reactive Form Select multiple selected values to Checkbox

The form is having 1 textbox , 1 radio button and 1 multi select Checkbox The HTML template is like below

        <form  *ngIf="notificationSettings | async; else loading"
              [formGroup]="notificationForm" (ngSubmit)="onSubmit()">
              
          <div class="form-group">        
            <div *ngFor="let option of notifyBackAlertOptions; let i=index">
              <input type="checkbox" class="form-check-input" [value]="option.value" (change)="onNotifyBackCheckboxChange($event)"  />
              <label>  </label>
            </div>
          </div>
          <div class="form-group">
            <label for="notifyBackEmail">Where shall we send the alerts?</label>
            <input type="email" class="form-control" formControlName="notifyBackEmail">
          </div>
          
          <div class="form-check" *ngFor="let option of discontinuedAlertOptions;">
            <label>
              <input formControlName="discontinuedOption" class="form-check-input"
                     type="radio"
                     name="discontinuedOption"
                     [value]="option.value" />
              
            </label>
          </div>

          <div class="float-left">
            <button class="btn btn-primary mr-1">Update</button>        
          </div>

        </form>

        <ng-template #loading>
          Loading ---...
        </ng-template>
        

The component is like below

    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';


    export class NotifcationsComponent implements OnInit {
      
      notificationSettings: Observable<NotificationSetting>;
      notificationForm: FormGroup;
      submitted = false; 
      
      notifyBackAlertOptions = [
        { name: 'Option 1', value: '1' },
        { name: 'Option 2', value: '2' },
        { name: 'Option 3', value: '3' }, 
        { name: 'Option 4', value: '4' }    
      ];
      discontinuedAlertOptions = [
        { name: 'Yes for any', value: '1' },   
        {name: 'Yes for all', value: '2' },
        { name: 'No', value: '3' }
      ];   

      constructor(private formBuilder: FormBuilder,private userService: UserService)  { }

      ngOnInit() {

        this.getCurrentSettings(); 
        this.notificationForm = this.formBuilder.group({
          notifyBackEmail: [''], 
          discontinuedOption: [''],   
          notifyBackOptions: new FormArray([]),
        });
        
        
      }

      getCurrentSettings(): void {

         //https://coryrylan.com/blog/using-angular-forms-with-async-data
         this.notificationSettings = this.userService
          .getUserNotificationSettings()
          .pipe(tap(data => this.notificationForm.patchValue(data)));
          
          //This code maps / sets the values of textbox and radio buttons correctly at page loading based on response from API. But not setting values for multiselect checkbox       
         //How to set the notifyBackOptions checkbox selected values marked as checked 
      }

      // convenience getter for easy access to form fields in HTML page 
      get f() { return this.notificationForm.controls; }
     

      onNotifyBackCheckboxChange(e) {
        const notifyBackOptions: FormArray = this.notificationForm.get('notifyBackOptions') as FormArray;

        if (e.target.checked) {
          notifyBackOptions.push(new FormControl(e.target.value));
        } else {
          let i: number = 0;
          notifyBackOptions.controls.forEach((item: FormControl) => {
            if (item.value == e.target.value) {
              notifyBackOptions.removeAt(i);
              return;
            }
            i++;
          });
        }
      }


      onSubmit() {
        this.submitted = true; 
        // stop here if form is invalid
        if (this.notificationForm.invalid) {
          return;
        }
        console.log(this.notificationForm.value);        
      }

       

    }
    

The HTML is rendering correctly and capturing the values at form submission . At load time of the component i have to read the values from API endpoint and prefill form based on current settings

The JSON response from API endpoint is like below

    {
    notifyBackEmail: "email@email-domain.in"
    notifyBackOptions: ["1","2"]
    discontinuedOption: "1"
    }

The existing implementation of getCurrentSettings() is setting values of radio and textbox but not checkbox. How can i set the Checkbox values as selected




Aucun commentaire:

Enregistrer un commentaire