Reputation: 462
How do I pass an array from template to component file. I have an if
condition which is dependent on the index of the loop. Please help me to find the right approach. Something like this
https://jsfiddle.net/HB7LU/7638
<ul>
<li *ngFor="let data of list_value | keyvalue; let i=index;" (click)="getListValue(i,data)">
<li>
<ul>
<li *ngFor="let item of data.value" *ngIf="data[i].active">
<li>
<ul>
<ul>
example.componet.ts file
export class SomeComponent{
list_value: Array<any> = [];
active: boolean;
getListValue(index: String, data: any) {
console.log("Test",data[index]);
list_value[index].active = !list_value[index].active
}
}
Upvotes: 0
Views: 8576
Reputation: 49
Hopefully below code will helpful
<ul>
<li *ngFor="let data of list_value;let i=index" (click)="getListValue(i,data)">
<span>{{data.name}}</span>
<ul>
<li *ngFor="let subItem of data.subItems" [hidden]="!data.active">
<span>---{{subItem.name}}</span>
</li>
</ul>
</li>
</ul>
Component ts
export class SomeComponent{
list_value: Array<any> = [
{
name: "Item1",
subItems: [
{name: "SubItem1"},
{name: "SubItem2"}
]
},
{
name: "Item2",
subItems: [
{name: "SubItem3"},
{name: "SubItem4"},
{name: "SubItem5"}
]
},
{
name: "Item3",
subItems: [
{name: "SubItem6"}
]
}
];;
getListValue(index: number, data: any) {
this.list_value[index].active = !this.list_value[index].active
}
}
Workign App https://stackblitz.com/edit/angular-gtqnmh
Upvotes: 0
Reputation: 2165
One of the way to pass data to component is by using @input
in angular like this:
<ul>
<li *ngFor="let data of list_value | keyvalue; let i=index;" (click)="getListValue(i,data)">
<li>
<ul>
<li *ngFor="let item of data.value" *ngIf="data[i].active">
<app-selector *ngSwitchCase="'observations'" [inputdata]=item></app-selector>
<li>
and in your component.ts
file which loads inside *ngFor
:
import { Component, OnInit, Input, NgModule, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-selector',
templateUrl: './selector.component.html',
styleUrls: ['./selector.component.scss']
})
export class ObservationsComponent implements OnChanges{
@Input() inputdata: any;
}
ngOnChanges() {
console.log(this.inputdata)
}
Upvotes: 2
Reputation: 421
If you want to pass the array, just pass the list_value. *ngFor is just like a for loop, it iterates over an array. Data itself maybe an array (as it is of type 'any'). But the index you are sending in the function is the index where data is in list_value[index]
Write *ngIf="data.active"
Also as it is shown in the link given, you don't need the index. Just write data.active = !data.active
Upvotes: 0