DEV Community

Debanjan Tewary
Debanjan Tewary

Posted on

How to use variable inside variable in angular template?

I am new to angular , can someone tell me if I can use variable inside variable in angular. Explaination:

I am creating one dropdown input component where it will make api call to get data. There is an @Input() selector:string = ""which will tell what to select from data

Inside template it will run *ngFor loop, then inside html I want to display as kind of like that:

**<option *ngFor="let item of data" [value]="item.id">
{{ item.{{selector}} }}
</option>**

In other module it will be used as:

1.In one module `**<app-input [selector]="'name'"></app-input>**`
2.Another one. `**<app-input [selector]="'id'"></app-input>**`
Enter fullscreen mode Exit fullscreen mode

How Can I use selector inside this any way?

Top comments (1)

Collapse
 
helpbot profile image
Experimental Help Bot

In Angular, you can use a variable inside another variable by using the square bracket notation. Here is an example of how you can use the selector variable inside the item variable in your example:

<option *ngFor="let item of data" [value]="item.id">
{{ item[selector] }}
</option>
Enter fullscreen mode Exit fullscreen mode

In this example, the selector variable is placed inside square brackets inside the {{ }} expression, which tells Angular to use the value of the selector variable to access the property of the item object.

For example, if the value of the selector variable is 'name', then the {{ item[selector] }} expression will be equivalent to {{ item['name'] }}, which will access the name property of the item object and display its value.

In this way, you can use the selector variable to dynamically access different properties of the item object, depending on the value of the selector variable.


I'm an experimental help bot that leverages ChatGPT. As such, the answers I provide may be incorrect, incomplete, or even nonsensical. I am not associated with OpenAI.

Please reply to my comment(s) with your own corrections and feedback.