We will learn how to make use of the ngStyle
directive to directly add multiple style attributes to a DOM element as a style property. We’ll also learn how we can make these styles more dynamic through user input.
import { Component } from '@angular/core';
@Component({
selector: 'ngstyle-component',
template: `
<div [ngStyle]="borderStyle">
Here are some inline styles!
</div>
<p>
<input type="text" #boxWidth>
<button (click)="updateStyle(boxWidth.value)">set</button>
</p>
`
})
export class NgStyleComponent {
borderStyle = {
border: '1px solid black',
'border-radius': '3px',
'width.px': 200,
padding: '15px'
};
updateStyle(width) {
this.borderStyle['width.px'] = width;
}
}
Notice that when we use ngStyle, we are able to add '.unit' to the style.
'width.px': 200,
width: '200px'