Attribute Directives
* Angular mainly offers 2
type of built-in directives.
1. Attribute Directive
2. Structural Directive
Attribute Directive
* Attribute Directives listens & modifies
a behavior of html elements, properties, attributes & components.
* Many NgModules like RouterModule & FormsModule has their own
attribute directives. Some of common attribute directives are:
NgClass
* This attribute directive add or removes classes to
an elements.
* Using ngClass multiple classes can be applied/removed to an
element.
* To add/remove single classes always preferable to use class binding
instead ngClass.
NgStyle
* ngStyle directive used to set multiple
inline styles simultaneously & dynamically at a time.
* To set a single style always prefer single style binding but to
do multiple binding ngStyle helps.
NgModel
* This directive used for two way data-binding.
* To get complete information refer Part-13 of this session.
app.comonent.ts
import { Component } from '@angular/core';
import { IDropdownItem } from './Model/idropdown-item';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name: string = 'SKMDoteNet';
isBgRqrd: boolean = true;
isFontRqrd = true;
classToApply = {}; stylesToApply = {};
getClassesToApply() {
return this.classToApply = {
'bgColor': this.isBgRqrd,
'font': this.isFontRqrd
};
};
getStylesToApply() {
return this.stylesToApply = {
'font-weight': this.isFontRqrd ? 'bold' : 'normal',
'background-color': this.isBgRqrd ? 'green' : 'white'
};
};
};
app.comonent.html
<div>
<div>
<h3>ngClass Attribute Directive</h3>
<p [ngClass]='getClassesToApply()'>This paragraph uses ngClass directive.</p>
</div>
<br /><br />
<div>
<h2>ngStyle Attribute Directive</h2>
<p [ngStyle]='getStylesToApply()'>This paragraph uses ngStyle directive.</p>
</div>
<br /><br />
<div>
<input type="text" [(ngModel)]='name' />
<br /><br />
<p>The name in textbox is <b>{{name}}</b></p>
</div>
</div>
app.comonent.css
.bgColor{
background-color: magenta;
}
.font{
font-family: Arial, Helvetica, sans-serif;
font-size: medium;
font-weight: bold;
}
.shapeStyle{
height: 50px;
width: 500px;
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
No comments:
Post a Comment