5

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 2

11

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. :)

Sign up to request clarification or add additional context in comments.

3 Comments

Ha, this answered my question. I was actually just trying to figure out why [varName]="variable" was not working and then you answered it for me! Thanks a ton!
And yes, documents are great - my main issue is not knowing the terms to search for such as "property binding".
That's ok - it is always an uphill battle when one starts with a new framework. It also took me a while before I memorized core concepts and terms in Angular. Happy coding!
1

I suggest you read this first https://angular.io/guide/component-interaction

1 Comment

This got me onto the right path, thank you for taking the time to post.

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.