简体   繁体   中英

Angular Material Component Custom Attributes

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM