2. Directives
Angular Components are directives with a template. A directive modifies the DOM to change appearance, behavior or layout of DOM elements.
3 main types of directives in Angular:
- Components: directives with a template.
- Attribute directives: directives that change the behavior of a component or element.
- Structural directives: directives that change the behavior of a component or element by affecting the template.
Attribute Directives
NgClass and NgStyle are built-in directives that can modify any component or element.
NgStyle Directive
Modify a componen's or element's style attribute with this built-in directive:
import { Component } from '@angular/core';
@Component({
selector: 'app-style',
template: `
<p style="padding: 1rem;" [ngStyle]="{'color': 'red',
'font-weight': 'bold', 'borderLeft': borderLeftStyle}">
<ng-content></ng-content>
</p>
`
})
export class StyleComponent {
borderLeftStyle = '3px solid green';
}
Here, we are binding an expression, an object literal to the ngStyle directive, it must be enclosed in square brackets.
Styles moved into the component as a property object, which then gets assigned to the ngStyle directive using property binding:
import { Component } from '@angular/core';
@Component({
selector: 'app-style',
template: `
<p style="padding: 1rem;" [ngStyle]="specialStyles">
<ng-content></ng-content>
</p>
`
})
export class StyleComponent {
borderLeftStyle = '3px solid green';
specialStyles = {
'color': 'red',
'font-weight': 'bold',
'borderLeft': this.borderLeftStyle
};
}
AppComponent:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div class="row">
<h1>{{ title }}</h1>
<div class="col-md-6">
<app-style>
<p>This is some <i>projected</i> content.</p>
</app-style>
</div>
<div class="col-md-6">
<img [src]="imageUrl" style="width:60rem; border-radius:50%">
<i>My Polymer Princess</i>
</div>
</div>
`
})
export class AppComponent {
title = 'Angular Exploration';
imageUrl = '../assets/keras1.jpg';
}
NgClass Directive
The ngClass directive changes the class attribute that is bound to the component or element it is attached to.
Property binding:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div class="row">
<h1>{{ title }}</h1>
<div class="col-md-6">
<p [ngClass]="['warning']">
This is the super secret message.
</p>
</div>
<div class="col-md-6">
<img [src]="imageUrl" style="width:60rem; border-radius:50%">
<i>My Polymer Princess</i>
</div>
</div>
`,
styles: ['.warning { color: red; font-weight: bold; font-size: 1.5rem;}']
})
export class AppComponent {
title = 'Angular Exploration';
imageUrl = '../assets/keras6.jpg';
}
Structural Directives
NgIf, NgFor, NgSwitch