简体   繁体   中英

Enable Two-Way data binding on Angular 6 for input type checkbox inside *ngFor

Problem: Two-way data binding for checkbox in *ngFor directive

I have a template driven form in which I am using *ngFor to loop over few radio buttons. Based on one key, I show checkbox next to radio buttons in disabled state on page load. If user clicks on a radio button and if it has a corresponding checkbox, I enable its state. I can then click on checkbox.

However, I want to be able to disable previous checkbox and reset its value when user clicks on another radio button and thus pass the correct form values. (I show them as json in beloe code demo url)

Demo code example: https://stackblitz.com/edit/angular-ba8pfz

If you see the demo code, I should be able to reset the checkbox if I toggle between "Marvel Heroes" and "Dc Heroes"

Appreciate your time and suggestions.

You cannot simply set the checked attribute to false as that sets the content checked attribute to an empty string - which is the equivalent of true or checked. Hence the check mark goes away, but the Boolean state of the control is not changed. Have to change the Boolean state of the control. One simple way to do that is to generate a click or change event on the control.

Try this:

enableRecursive(event, recursiveChk: boolean) {
    let clickEvent = new MouseEvent('click');
    this.recursiveChk.map((elem) => {
      if (elem.nativeElement.checked) {
        elem.nativeElement.dispatchEvent(clickEvent);
      }
      elem.nativeElement.disabled = true;
      if (`recursive_${event.target.id}` === elem.nativeElement.id) {
        elem.nativeElement.disabled = false;
      }

    });

  }

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