lundi 21 juin 2021

Angular Reactive form set Multiselect Checkbox values

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" formControlName="notifyBackOptions"  />
              <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 {



        this.notificationSettings =   this.userService
          .getUserNotificationSettings()
          .pipe(tap(data => {
            console.log("GET")
         
            this.notificationForm = this.formBuilder.group({
              notifyBackEmail: new FormControl(data.notifyBackEmail),                 
              discontinuedOption: new FormControl(data.discontinuedOption),
              notifyBackOptions: new FormControl(data.notifyBackOptions)
            });

            console.log(this.notificationForm) //I can see the values are mapping correctly against notificationForm. Checkbox  property ie notifyBackOptions value is coming as ["1", "2"] at this stage 

            }        
           ));
          
          //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 correctly. 
            //I can see all checkbox values are coming as selected.          IN this case 4 checkbox values are selected      
         //How to set only  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; }
     

 

      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 correctly but not checkbox. At present this is setting all values of checkbox as selected. How can i set the Checkbox values as selected based on response form API with help of model binding




Aucun commentaire:

Enregistrer un commentaire