Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to pass an inline style to component

I have created a custom component. The component's HTML scaffolding contains very simple HTML.

<!-- Generated template for the MyComponent component -->
<div>
  {{text}}
</div>

But adding a style like this did not work.

<my-component style="height:300px; background:gray;"></my-component>

I think I need to pass that style to the <div>. But how?

like image 246
Damn Vegetables Avatar asked Dec 11 '17 19:12

Damn Vegetables


People also ask

How do I create a component with an inline template?

But when we want to generate component with inline template and style we have to provide two options after the above command. For inline templates, we need to add --inlineTemplate=true. By default its value is false. For inline style, we need to add --inlineStyle=true.

How we can add style to the particular component in Angular?

There are several ways to add styles to a component: By setting styles or styleUrls metadata. Inline in the template HTML. With CSS imports.

Do external styles override inline styles?

It even overrides the inline styles from the markup. The only way to override is by using another ! important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code. Must Read - CSS Specificity by MDN 🔗


1 Answers

try (as already mentioned by @1.618)

<my-component [ngStyle]="{height:'300px', background:'gray', display: 'block'}">
</my-component>

applying only style (with display: block or inline-block) will also work:

<hello style="color: green; height:200px; background:yellow; display: block;" 
       name="Another name"></hello>

STACKBLITZ: https://stackblitz.com/edit/angular-hy6xpc?file=app%2Fapp.component.html

like image 151
Andriy Avatar answered Sep 21 '22 18:09

Andriy