Search code examples
htmlangularangular-ng-if

Angular ngIf using parent checkbox checked condition


I'm a bit stuck with my problem. I'm working on view like that:

enter image description here

I'm fetching data from API so I will have multiple options and suboptions. However I want suboption to appear only when parent checkbox is checked. I tried to use *ngIf:

 <ul *ngFor="let job of jobs; let i = index">
  <input type="checkbox" id="{{i}}" value="{{job.name}}"><label
   for="{{i}}">{{job.name}}</label>
  <ul *ngIf="CONDITION HERE">
   <li *ngFor="let child of job.children"><label><input type="checkbox"> 
    {{child.name}}</label></li>
   <li *ngFor="let child of job.children"><label><input type="checkbox"> 
    {{child.name}}</label></li>
  </ul>
</ul>

But I can't identify what condition could I use. Is there a simple solution to solve that?

@edit Let me clarify. I might have multiple options like that:

enter image description here

Using a flag won't work, because each parent options would have to use unique boolean variable.


Solution

  • You can achieve this with the help of template reference variable. Assign a template variable to all repetitive parent input checkbox elements.

    Use this variable to check the status of the checkbox (checked/unchecked) and based on this show/hide the children.

    Please note that you will have to also use

    (change)="true"
    

    for parent checkbox. Without this the checked/unchecked property of the checkbox will not change.

    Modify your template like this:

    <ul *ngFor="let job of jobs; let i = index">
      <input type="checkbox" id="{{ i }}" value="{{ job.name }}" (change)="true" #checkBox/><label
        for="{{ i }}"
        >{{ job.name }}</label
      >
      <ul *ngIf="checkBox.checked">
        <li *ngFor="let child of job.children">
          <label><input type="checkbox" /> {{ child.name }}</label>
        </li>
        <li *ngFor="let child of job.children">
          <label><input type="checkbox" /> {{ child.name }}</label>
        </li>
      </ul>
    </ul>
    

    Stackblitz: https://stackblitz.com/edit/angular-x3coln?file=src/app/app.component.html