2

I have created a component whose sole purpose is to display the color palette hues for a given palette (primary, secondary, accent, emphasis, warn)

I want to allow the component to be added to any page using the component template (my-color-palette-component) and color attribute (primary, secondary, accent, etc) specified as:

<my-color-palette-component color="primary"></my-color-palette-component>

How can I retrieve the value of the color attribute and insert it into my component.html as the class attribute?

Example, in my my-color-palette-component.component.html code:

<div class={{this.color?}}>
  ...markup
</div>

So that the DOM markup becomes:

<div class="primary">...markup</div>

1 Answer 1

2

First you have to declare the variable color in your component and mark it as an input(if you haven't done so yet):

@Input() public color:string; //Remove the typings in case you're not using typescript

After that you can simply set the class attribute like this:

<div [class]="color">...markup</div>

One thing to note is that this will completely override a class attribute you directly set in your template:

<div class="someOtherClass" [class]="color">...markup</div>

Assuming that color has the value primary this would result in the following:

<div class="primary">...</div>

In a case like this you can use ngClass:

<div class="someOtherClass" [ngClass]="color">...markup</div>
Sign up to request clarification or add additional context in comments.

2 Comments

That was easy! Thanks for the help. If you have a suggestion for a good tutorial series on developing components, please share.
angular.io itself has pretty good guides. This part right here might be of interest to you: angular.io/guide/component-interaction

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.