Try this
<div class="home-component"
[style.width.px]="width"
[style.height.px]="height">Some stuff in this div</div>
[Updated]: To set in % use
[style.height.%]="height">Some stuff in this div</div>
To use % instead of px or em with @Gaurav's answer, it's just
<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>
This should do it:
<div class="home-component"
[style.width]="width + 'px'"
[style.height]="height + 'px'">Some stuff in this div</div>
You can also use hostbinding:
import { HostBinding } from '@angular/core';
export class HomeComponent {
@HostBinding('style.width') width: Number;
@HostBinding('style.height') height: Number;
}
Now when you change the width or height property from within the HomeComponent, this should affect the style attributes.
The accepted answer is not incorrect.
For grouped styles one can also use the ngStyle directive.
<some-element [ngStyle]="{'font-style': styleExpression, 'font-weight': 12}">...</some-element>
The official docs are here
If you want to set width dynamically with variable than use [] braces instead {{}}:
<div [style.width.px]="[widthVal]" [style.height.px]="[heightVal]"></div>
<div [style.width.%]="[widthVal]" [style.height.%]="[heightVal]"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With