jeudi 26 novembre 2020

angular - How to do dynamic default checked checkboxes with reactive forms

I have a edit profile form. for has dynamic checkbox. if user updated the check box once then it should checked default.

Here is my ts file...

import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ApplicantsService } from '@app/services/applicants.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  myForm: FormGroup;
  submitted = false;
 
  userid: any;
  
  skills: any;
  experience: any;
  applicant_skills: any;
  profile: any;
  states: any;
  cities: any;
  profilePicture: any;

  constructor(
    private formBuilder: FormBuilder,
    private applicantsService: ApplicantsService,
  ) { }

  ngOnInit(): void {
    
    this.userid = JSON.parse(localStorage.getItem('currentUser')).user_id;

    this.myForm = this.formBuilder.group({
      userid: [''],
      first_name: new FormControl({value: null, disabled: true}, Validators.required),
      last_name: new FormControl({value: null, disabled: true}, Validators.required),
      email: new FormControl({value: null, disabled: true}, Validators.required),
      mobile: ['', Validators.required],
      state: ['', Validators.required],
      city: ['', Validators.required],
      skills: this.formBuilder.array([], [Validators.required]),
    });
    
    this.applicantsService.getProfile(this.userid).subscribe( res => {
      this.profile = res.data[0];
      this.myForm.patchValue(this.profile); 
    })

    this.applicantsService.getApplicantskills(this.userid).subscribe( res => 
    {
      if(res && res.data)
      {
        this.applicant_skills = res.data;
        
        
      }
    })


  }


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

 


  onCheckboxChange(e) {
    const checkArray: FormArray = this.myForm.get('skills') as FormArray;

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

  onSubmit()
  {
      this.submitted = true;

      // stop here if form is invalid
      if (this.myForm.invalid) {
        console.log(this.myForm)
        return;
      }

      console.log("this.myForm.value", this.myForm.value);
      
  }

}

Here is my html page.

<!-- Spinner -->
<ngx-spinner></ngx-spinner>

<section id="profile-form" class="bg-grey">
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-lg-10 col-md-12">
          
          <h1 class="text-center">Update your profile</h1>

          <div class="form p-md-6">

              
              <form  [formGroup]="myForm" (ngSubmit)="onSubmit()">

                <div class="form-row">
                    <div class="form-group d-none">
                        <input type="text"  formControlName="userid" value=>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="linkedin">First Name</label>
                        <input type="text" class="form-control" formControlName="first_name" placeholder="First Name">
                    </div>
                    <div class="form-group col-md-6">
                        <label for="lastname">Last Name</label>
                        <input type="text" class="form-control" formControlName="last_name" placeholder="Last Name">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="linkedin">Email ID</label>
                        <input type="email" class="form-control" formControlName="email" placeholder="Email ID">
                    </div>
                    <div class="form-group col-md-6">
                        <label for="lastname">Cellphone Number</label>
                        <input type="text" class="form-control" formControlName="mobile" placeholder="Cellphone Number" [ngClass]="{ 'is-invalid': submitted && f.mobile.errors }" required>
                        <div *ngIf="submitted && f.mobile.errors" class="invalid-feedback">
                            <div *ngIf="f.mobile.errors.required">This field is required</div>
                        </div>
                    </div>
                </div>

                

                  
                  <div class="form-row">
                      <div class="button-group-pills text-center col-md-12" data-toggle="buttons">

                        <label class="btn btn-default" *ngFor="let skill of skills">
                            <input type="checkbox" formArrayName="skills" (change)="onCheckboxChange($event)" value= [ngClass]="{ 'is-invalid': submitted && f.skills.errors }" required>
                            <div></div>
                        </label>
                        <div *ngIf="submitted && f.skills.errors" class="error">
                            <div *ngIf="f.skills.errors.required">This field is required</div>
                        </div>
                      </div>
                      
                  </div>



                  <div class="form-row justify-content-center text-center pt-4 pb-2">
                      <div class="col-md-8">
                          <button type="submit" class="btn btn-apply px-4">save profile</button>
                      </div>
                  </div>
              </form>
          </div>
              
        </div>

      </div>
    </div>
  </section>

Please help .........................................................................................................................................................................................................................................................................




Aucun commentaire:

Enregistrer un commentaire