How to pass variables in an Angular selector

Viewed 8296

I have an angular charComponent that creates pie, and line and other graphs which I want to embed in various places in my app.

I use the selector:

<chart></chart>

To expose a chart.

What I want to do is embed a variable into the code so I can tell the component what chart I want returning.

So something like this:

<chart variable="pie-chart"></chart>

Is something like this possible or is there a better way to do it?

2 Answers

It is called property binding and is one of the core concepts you should/will be using with Angular.

  1. Define the variable, which will be passed to your ChartComponent as

    export class ChartComponent {
    
      @Input() public varName: string; // this is typed as string, but you can use any type you want
    
      constructor() {}
    }
    
  2. Now you can use

<chart [varName]="varValue"></chart>

OR

<chart varName="varValue"></chart>

to pass the variable value to the ChartComponent. The difference between the two notations is that with the first one you pass the varValue, which will be evaluated; whereas in the second notation the varName value IS 'varValue'.

And yes, the Angular docs are sometimes quite good. :)

Related