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
If I understand you correctly, the answer to your question is here
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:
child.component.ts:
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.