4

Say I have an angular component ie <this-thing></this-thing> which does it's thing.

Now I want to add something extra to it, ie <this-thing glows></this-thing> I would like the component to change a little if the glow attribute is there.

I have managed to do it via <this-thing [glows]="true"></this-thing> and in the component I have

@Input() public set glows(value: boolean) {
    console.log(value);
}

But that becomes too verbose.

If glows attribute is not on the component, then it's false and if it is, then true.

Is there a better way to acheive this?

Thanks for looking.

3 Answers 3

10

use @Attribute and @optional in constructor see the docs

constructor(@Optional() @Attribute('glow') glow: any) {
  console.log(glow)
  console.log(glow==undefined)
}

<hello glow></hello> //give you '',false
<hello></hello> //give you null,true
Sign up to request clarification or add additional context in comments.

1 Comment

this is the exact answer. Thank you! Works very well.
0

I think it depends on what you are trying to achieve. If it is just a boolean value to use in the component/template I don't think you need the setter, so that

@Input() glows : boolean;

in the this-thing.component.ts would be sufficient.

In the this-thing.component.html you could then bind a specific class to the dom element with ngClass

<div [ngClass]="{'glows': glows}">This glows if true</div>

this-thing.component.css

.glows {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

1 Comment

Thank you yax, and welcome. I already had an @Input solution but wanted something that didnt take variables.
0

You can achieve this with the @HostBinding decorator which allows you to change the attribute later inside your code.

Example code for glows attribute in the component code

@HostBinding('attr.glows')
public glows: boolean;

this.glows = true; // Sets the glows attribute
this.glows = false; // Removes the glows attribute

Example code for glows attribute in the component styles

:host([glows]) {
  /* Custom styles for component when the attribute is present */
} 

1 Comment

Thank you for replying. I kinda had this setup already with the @Input decorator. I wanted a pure if there or if not there solution. Much appriciated.

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.