dimanche 13 juin 2021

Checkboxes are checked but they have no initial value on page reload

The current setup works find when i check/uncheck boxes and submit to server.

however, when the page reloads or when i go to edit, the page loads fine and the checkbox is checking the right entries like this...

enter image description here

The problem here is when i click submit without touching any values, the array is submitted empty permission_ids: [], they need to be clicked again in order to fire the OnChange() and i can't do this automatically when i page loads since i'm new to Angular

So the issue here as i understand, that the checkboxes are checked but the value of the form isn't updated.

here are the code

Template

<h4>Permissions</h4>
            <div class="form-group row p-t-20">
              <div class="col-sm-4">
                <div class="custom-control custom-checkbox" *ngFor="let perm of permissions; let i=index">                
                  <input
                    type="checkbox"
                    class="custom-control-input"
                    id="permission_"
                    [value]="perm.id"
                    (change)="onPermissionCheckboxChange($event)"
                    [checked]="permissionExists(perm.id)">
                  <label
                    class="custom-control-label"
                    for="permission_">
                    
                  </label>
                </div>
              </div>
            </div>

TS

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators  } from "@angular/forms";
import { NotificationService } from "../../notification/notification.service";
import { PermissionsService } from "../../permissions/permissions.service";
import { HttpClient } from "@angular/common/http";
import { environment } from "../../../../environments/environment";
import { Router, ActivatedRoute } from "@angular/router";
import { RolesService } from "../roles.service";

@Component({
  selector: 'app-edit-role',
  templateUrl: './edit-role.component.html',
  styleUrls: ['./edit-role.component.css']
})
export class EditRoleComponent implements OnInit {
  isLoading: boolean = false;
  roleId: number = +this.route.snapshot.params['id']
  roleObj: any = {};
  haveRole: any = true;
  roles: any;
  role: any;

  permissions: any;

  form: FormGroup;

  constructor(
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private notificationService: NotificationService,
    private rolesService: RolesService,
    private permissionsService: PermissionsService
  ) {
    this.form = this.fb.group({
      role: new FormGroup({
        name: new FormControl('', [Validators.required]),
        permission_ids: this.fb.array([])
      })
    })
  }

  permissionExists(id: number) {
    return this.role.permissions.find(function(el: any){ return el.id === id }) !== undefined;
  }

  ngOnInit(): void {
    this.rolesService.getRoles().subscribe(response => {

    this.roles = response.body;
    this.role = this.roles.find((el: any) =>  el.id === this.roleId)

    //console.log(this.role);
    this.isLoading = false;
    this.form.patchValue({
      'role': {
        'name': this.role.name
      }
    });
    },
    error => {
      this.isLoading = false;
      this.notificationService.showNotification(
        error.error.title,
        error.error.details,
        'error'
      );
    })

    
    this.permissionsService.getPermissions().subscribe(response => {

      this.permissions = response.body;
      this.isLoading = false;
    },
    error => {
      this.isLoading = false;
      // console.log(error.error);
      this.notificationService.showNotification(
        error.error.title,
        error.error.details,
        'error'
      );
    })
  }


  onPermissionCheckboxChange(e: any) {
    const checkArray: FormArray = this.form.get('role.permission_ids') as FormArray;
if (e.target.checked) {
      checkArray.push(new FormControl(e.target.value));
    } else {
      let i: number = 0;
      checkArray.controls.forEach((item: any) => {
        if (item.value == e.target.value) {
          checkArray.removeAt(i);
          return;
        }
        i++;
      });
    }
  }

  onSubmit() {
    this.roleObj.role = this.form.value.role
    console.log(this.roleObj)
  }
}

Excuse my poor code but I'm still learning angular as i'm mainly Ruby on Rails developer




Aucun commentaire:

Enregistrer un commentaire