mercredi 27 juin 2018

Angular 5 - Uncheck all checkboxes function is not affecting view

I'm trying to include a reset button on a Reactive form in Angular 5. For all form fields, the reset is working perfectly except for the multiple checkboxes, which are dynamically created.

Actually the reset apparently happens for the checkboxes as well, but the result is not reflected in the view.

service.component.html

<form [formGroup]="f" (ngSubmit)="submit()">
  <input type="hidden" id="$key" formControlName="$key">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" formControlName="name">
  </div>
  <br/>
  <p>Professionals</p>
  <div formArrayName="prof">
    <div *ngFor="let p of professionals | async; let i = index">
      <label class="form-check-label">
      <input class="form-check-input" type="checkbox (change)="onChange({name: p.name, id: p.$key}, $event.target.checked)" [checked]="f.controls.prof.value.indexOf(p.name) > -1"/></label>
    </div>
    <pre></pre>
  </div>
  <br/>
  <button class="btn btn-success" type="submit" [disabled]="f?.invalid">Save</button>
  <button class="btn btn-secondary" type="button" (click)="resetForm($event.target.checked)">Reset</button>
</form>

service.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators, FormArray } from '@angular/forms'

import { AngularFireAuth } from 'angularfire2/auth';
import { Router, ActivatedRoute } from '@angular/router';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable} from 'angularfire2/database';
import { Service } from './service';

export class ServiceComponent implements OnInit {

  f: FormGroup;

  userId: string;
  $key: string;
  value: any;
  services: FirebaseListObservable<Service[]>;
  service: FirebaseObjectObservable<Service>;
  professionals: FirebaseListObservable<Service[]>;
  profs: FirebaseListObservable<Service[]>;

  constructor(private db: AngularFireDatabase, 
              private afAuth: AngularFireAuth,
              private route: ActivatedRoute, 
              private router: Router,
              private fb: FormBuilder) { 

    this.afAuth.authState.subscribe(user => {
      if(user) this.userId = user.uid
        this.services = db.list(`services/${this.userId}`);
    })

    this.afAuth.authState.subscribe(user => {
      if(user) this.userId = user.uid
        this.professionals = this.db.list(`professionals/${this.userId}`);
    })

  }

  ngOnInit() {   

    // build the form
    this.f = this.fb.group({
      $key: new FormControl(null),
      name: this.fb.control('', Validators.required),
      prof: this.fb.array([], Validators.required)
    })
  }

   onChange(name:string, isChecked: boolean) {
    const profArr = <FormArray>this.f.controls.prof;

    if(isChecked) {
      profArr.push(new FormControl(name));
      console.log(profArr.value);
    } else {
      let index = profArr.controls.findIndex(x => x.value == name)
      profArr.removeAt(index);
      console.log(profArr.value);
    }
  }

   resetForm(){
    let profArr = <FormArray>this.f.controls.prof;

    this.f.controls.name.setValue('');
    profArr.controls.map(x => x.patchValue(false));
    this.f.controls.$key.setValue(null);
   }
}

service.ts

export class Service {
    $key: string;
    name: string;
    professionals: string[];
  }

The result of the code above, displayed by line <pre> </ pre> is:

When I fill out the form:

{
  "$key": null,
  "name": "Test service",
  "prof": [
    {
      "name": "Ana Marques",
      "id": "-LEZwqy3cI3ZoYykonWX"
    },
    {
      "name": "Pedro Campos",
      "id": "-LEZz8ksgp_kItb1u7RE"
    }
  ]
}

When I click on Reset button:

{
  "$key": null,
  "name": "",
  "prof": [
    false,
    false
  ]
}

But checkboxes are still selected:

enter image description here

What is missing?




Aucun commentaire:

Enregistrer un commentaire