0

I've created a list component, running successfully through an array of items and outputting its data through an *ngFor loop.

now I want to reuse this component and add more possible arrays of data to choose from. for that, an @input was created, allowing me to pass the array name "on" the component wherever it's used, but when I try to pass it to the *ngFor I get an error.

my ts code is:

@Input() listName : string;
list1: any = [
 {title: 'title1'},
 {title: 'title2'},
 {title: 'title3'},
]
list2: any = [
 {title: 'titlea'},
 {title: 'titleb'},
 {title: 'titlec'},
]

the component looks like this:

<app-listcomp listName="list1"></app-listcomp>

I can figure that this is not a correct syntax inside the component:

*ngFor="let listItem of {{listName}}"

but can't quit find what is the correct way to pass the array name through the @Input (or any other correct way).

when I use the specific array name in the *ngFor loop - it works perfectly of course.

1
  • if listName is an array as input then it should be *ngFor="let listItem of listName", post the component code too. Commented Jun 5, 2019 at 7:51

2 Answers 2

1

Well you can do something like this

Class:

getList() {
  return this[this.listName];
}

Template:

*ngFor="let listItem of getList()"
Sign up to request clarification or add additional context in comments.

2 Comments

Er...you pass the list you want to retrieve. Isn't it a bit dumb?
Yeah I know, its an alternative solution for your requirements, because you cannot do interpolation in *ngFor
0

There are several solutions but it depends on the global context and what you need really need.

The most simple solution is just to directly give the expected array to the component.

In the component code:

@Input()
myList: any[];

In the template:

*ngFor="let listItem of myList"

But if you really need it to work as mention it in you question, just use a method. Of course, you will need to pass a dictionary (or map) of arrays indexed by their name.

In the component code:

@Input()
myLists: {[name: string]: any[]}; // dictionary of arrays indexed by name

getList(name: string): any[] {
   return this.myLists[name];
}

In the template:

*ngFor="let listItem of getList('the name I want')"

Edit

From what I see in your question since you edited I can give you an answer that is closer to what you expect.

In the component code:

get selectedList(n): any[] {
   return this[this.listName];
}

In the template:

*ngFor="let listItem of selectedList"

1 Comment

I have updated my code example for more info about my question. If you can please refer to it in your example it'll be great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.