08 Jan 2018
angular directives
Currently enrolled in Udemy’s- the complete guide to angular 2. Notes from Lesson 1 and 2
Link to Assignment 3 - Directives
What are Directives?
- A directive is an instruction for a DOM element
- It is a marker on a DOM element (attribute, element name, CSS class) that Angular uses to compile to the HTML (
$compile
) and attach the instruction to the DOM element and its children
Structural Directives
- annotated by the *
-
*ngIf
and*ngFor
are most commonly used -
Example:
<p *ngIf="expression">Show me!</p>
ngIf
-
directive that conditionally adds or remove content from the DOM based on whether or not the expression evaluates to true or false
*ngIf
else- can use the
ng-template
directive with a marker forelse
conditions
- can use the
-
Example:
<p *ngIf="conditional expression; else markerThatMatchesngTemplate"> I satisfied the if statement</p> <ng-template #markerThatMatchesngTemplate> <p>I satisfy the else statement</p>
Attribute Directives
- attribute directives only change the element that they were placed on. They don’t add or remove elements, unlike structural directives.
ngStyle & ngClass
- directives that allow you to set CSS styling on an HTML element conditionally.
- NOTE:
- for class name (
ngClass
):- single quotes for dash syntax
[ngClass]="{'css-class': conditionExpressionOrMethod()}"
- camel case
[ngClass]="{cssClass: conditionExpressionOrMethod()}"
- single quotes for dash syntax
- for class name (
-
Example:
<p [ngStyle]="{cssStyle: conditonalMethod()}" [ngClass]="{cssClass: conditionExpressionOrMethod()}"> This text will be styled according to the above expressions </p>
ngFor
- directive that displays an iterable data structure.
- remember to use the
let oneItem of iterable
syntax!
<p *ngFor="let item of items">{{ item.name }}</p>
Til next time,
lovelejess
at 17:45