简体   繁体   中英

Angular 6 - Click event binding not working for checkbox

I am using reactive form to present a list of heroes to user and want to trigger a console log when user selects a hero by clicking on checkbox.

So, the problem is when i print this.form in console I get the correct value, but when i print this.form.value, I get the value of previous state.

Screenshot of when 1 Hero is selected

选择了 1 个英雄

As you can see, when 1 hero is selected, this.form is printing the correct values but this.form.value is printing the previous state, ie when no values were selected.

Screenshot of when 2 Hero is selected

选择了 2 个英雄

Similarly for 2 heroes. Showing result of previous state, ie when 1 hero is selected.

The code for the same is below.

 <div class="lists">
  <form [formGroup]="form" (submit)="select()">
      <ul formArrayName="assets" class="heroes p-2">
      <li class="p-2" *ngFor="let asset of form.controls.assets.controls; let i = index"
          [class.selected]="hero === selectedHero"
          (click)="select()">
          <input type="checkbox" [formControlName]="i">
          {{heroes[i].name}}
      </li>
      </ul>
      <button>submit</button>
  </form>
</div>

component.ts

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

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

  form: FormGroup;
  selectedHero;
  heroes = [
    { id: 11, name: 'Dr Nice', isChecked: false },
    { id: 12, name: 'Narco', isChecked: false },
    { id: 13, name: 'Bombasto', isChecked: false },
    { id: 14, name: 'Celeritas', isChecked: false },
    { id: 15, name: 'Magneta', isChecked: false },
    { id: 16, name: 'RubberMan', isChecked: false },
    { id: 17, name: 'Dynama', isChecked: false },
    { id: 18, name: 'Dr IQ', isChecked: false },
    { id: 19, name: 'Magma', isChecked: false },
    { id: 20, name: 'Tornado', isChecked: false },
  ];

  constructor( private formBuilder: FormBuilder,) {
                this.form = this.formBuilder.group({
                  assets: new FormArray([])
                });
                this.addCheckboxes();
              }

  ngOnInit() {
  }

  private addCheckboxes() {
    this.heroes.forEach((o, i) => {
      const control = new FormControl();
      (this.form.controls.assets as FormArray).push(control);
    });
  }

  select() {
    console.log(this.form);
    console.log(this.form.value);
  }

  onSelect(hero): void {
    this.selectedHero = hero;
  }

}

Please help.

    <div class="lists">
  <form [formGroup]="form" (submit)="select()">
      <ul formArrayName="assets" class="heroes p-2">
      <li class="p-2" *ngFor="let asset of form.controls.assets.controls; let i = index"
          [class.selected]="hero === selectedHero"
          >
          <input type="checkbox" [formControlName]="i" (change)="select()">
          {{heroes[i].name}}
      </li>
      </ul>
      <button>submit</button>
  </form>
</div>

Seems like the "click" event handler is executed before the form object is updated. As shown in the other answer, a "change" event handler will update the form as expected.

Confusion is caused by the visualisation of the form object in the browser console. When you log this.form, you see its properties with their latest values. When you log this.form.value, you get the current value of that property and this is its actual value in the moment of logging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM