mercredi 4 mai 2022

How to get the values of default checked checkbox

I was working on a project of multiple checkbox. There, I want the checkboxes to be checked from the start and the value to be in the form(I am using reactive form). The user can unselect the boxes according to their wish and the data will be stored accordingly. This is the stackblitz of the project. There I was able to make the checkbox checked from the beginning, but when I hit the submit button there is no data when I console-logged. I think this is some binding issue,but I couldn't figure out what is exactly the problem. Can someone help? Thanks in advance.

This is code:

<form [formGroup]="form" (ngSubmit)="submit()">
  <div class="form-group">
    <label for="website">Website:</label>
    <div *ngFor="let web of websiteList">
      <label>
        <input
          type="checkbox"
          [value]="web.id"
          (change)="onCheckboxChange($event)"
          [checked]="web.isSelected"
        />
        
      </label>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit</button>
</form>
  form: FormGroup;
  websiteList: any = [
    { id: 1, name: 'HDTuto.com', isSelected: true },

    { id: 2, name: 'HDTuto.com', isSelected: true },

    { id: 3, name: 'NiceSnippets.com', isSelected: true },
  ];

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      website: this.fb.array([], [Validators.required]),
    });
  }

  ngOnInit() {}
  onCheckboxChange(e: any) {
    const website: FormArray = this.form.get('website') as FormArray;
    console.log('checking ->', e);

     if (e.target.checked) {
      website.push(new FormControl(e.target.value));
      console.log('website ->', website);
    } else {
      //console.log(e);
      const index = website.controls.findIndex((x) => {
        console.log('x.value ->', x.value);
        console.log('target.value ->', e.target.value);
        x.value === e.target.value;
      });

      website.removeAt(index);
    }
  }
  submit() {
    console.log(this.form.value);
  }



Aucun commentaire:

Enregistrer un commentaire