skip to Main Content

I have a parent component with data that I want to pass to a child component using the ngFor directive, but when some array has no length I want to pass an input telling the child that the array is empty. How to achieve that?

parent.comp

const data = {one: [{a:1}, {a:2}, {a:3}],
        two: [],
        three: [{a:4}, {a:5}],
        four: [],
        five: []
        six: [{a:6}]
       }

<div *ngFor="let numbers of data | keyvalue">
      {{numbers.key}}
      <child-comp *ngFor="let item of data[numbers.key]">
        {{item.a}}
        [item]="item"
        [isEmpty]="isEmpty" //should be true to two, four and five keys
      </child-comp>
<div>

child.comp

@Input() item;
@Input() isEmpty; //should receive the values from parent

<div class="items">
    <div [ngClass]="isEmpty? 'empty' : 'full'">item.a</div>
</div>

2

Answers


  1. If I understand you correctly, the answer to your question is here

    Login or Signup to reply.
  2. To achieve communication between the parent and child components using the ngFor directive and pass the information about whether the array is empty or not, you can make the following adjustments to your code:

    parent.component.ts:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-parent',
      template: `
        <div *ngFor="let numbers of data | keyvalue">
          {{ numbers.key }}
          <app-child
            *ngFor="let item of data[numbers.key]"
            [item]="item"
            [isEmpty]="data[numbers.key].length === 0"
          ></app-child>
        </div>
      `,
    })
    export class ParentComponent {
      data = {
        one: [{ a: 1 }, { a: 2 }, { a: 3 }],
        two: [],
        three: [{ a: 4 }, { a: 5 }],
        four: [],
        five: [],
        six: [{ a: 6 }],
      };
    }
    

    child.component.ts:

    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'app-child',
      template: `
        <div class="items">
          <div [ngClass]="isEmpty ? 'empty' : 'full'">{{ item.a }}</div>
        </div>
      `,
    })
    export class ChildComponent {
      @Input() item;
      @Input() isEmpty: boolean;
    }
    

    In the parent component, we iterate through the data object using *ngFor and get the key-value pairs using the KeyValuePipe. For each key, we pass the corresponding array and a boolean indicating whether the array is empty or not to the child component.

    In the child component, we receive the item and isEmpty inputs from the parent component and use them to conditionally apply the ’empty’ or ‘full’ CSS classes to the div element based on the value of isEmpty.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search