Style binding is a technique used by angular to define inline styles for any element dynamically.
The styles are defined in a function that can return a set of effects by using objects.
Syntax
public Effects() {
let styles= {
'color' :'red';
'font-weight' :'bold';
}
return style
}
The style are bound to any element by using "ngstyle" directive
Syntax:
<h2 [ngstyle]="Effects()" > Your Text </h2>
Example
Add a new component
ng g c stylebinding
.ts changes
import { Component } from '@angular/core';
@Component({
selector: 'app-stylebinding',
templateUrl: './stylebinding.component.html',
styleUrls: ['./stylebinding.component.css']
})
export class StylebindingComponent {
public backColor:any;
public textColor:any;
public Effects() {
let styles= {
'background-color' : this.backColor,
'color': this.textColor,
'text-align':'center'
};
return styles;
}
}
ScreenShot
html changes
<fieldset>
<legend> Select Effects</legend>
<dl>
<dt> Background Color</dt>
<dd>
<select [(ngModel)]="backColor" >
<option> Green </option>
<option> Blue </option>
<option> Red </option>
</select>
</dd>
<dt>Text Color</dt>
<dd>
<select [(ngModel)]="textColor">
<option> White </option>
<option> Yellow</option>
<option> Gray </option>
</select>
</dd>
</dl>
</fieldset>
<h2 [ngStyle]="Effects()"> Style Binding</h2>
Screenshot
AppModule.ts
Index.html
Output
No comments:
Post a Comment
Thank you for visiting my blog