Angular / Angular Templates
Introduction
See the Angular Template Syntax documentation.
This section provides a brief overview of how template syntax is used within Angular.
For Loops
For loops are created in Angular templates using *ngFor
.
This is a ''structural directive".
Structural directives shape or reshape the DOM's Structure, typically by adding, removing,
and manipulating the elements to which they are attached.
Any directive with an *
is a structural directive.
Example:
<h2> My Heroes </h2>
<ul class="heroes">
<li *ngFor="let hero of heroes">
... do something with `hero`
</li>
</ul>
If Statements
If statements are created using *ngIf
. This is also a structural directive.
It conditionally includes a portion of the template based on the value of an expression.
When the expression evaluates to true, Angular renders the template provided in a then
clause,
and when false or null, Angular renders the template provided in an optional else
clause.
The default template for the else
clause is blank.
Example:
<li *ngIf="show; else notShow">
... do something with `hero`
</li>
<ng-template #notShow>
... do something else
</ng-template>
Interpolation
Interpolation allows incorporation of calculated strings, or values passed in from the component class, into the text between HTML element tags and within attribute assignments. Template expressions are used to calculate the strings.
Interpolation refers to embedding an expression into marked up text.
By default, interpolation uses the double curly braces {{
and }}
as its delimiter.
Example:
<span>This heroes name is: {{hero.name}}</span>
Property Binding
Use property binding to set the property of target elements or directive @Input( )
decorators.
One-way In
Property binding flows a value in one direction, from a component's property into a target element property.
Property binding cannot be used to read or pull values out of target elements. Similarly, property binding cannot be used to call a method on the target element. If the element raises events, event binding can be used to listen to the events.
Example:
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
Event Binding
Event binding allows listening for certain events such as keystrokes, mouse movements, clicks, and touches.
Angular event binding syntax consists of a target event name within parentheses on the left of an equal sign,
and a quoted template statement on the right.
The following event binding listens for the button's click events,
calling the component's onSave()
method whenever a click occurs:
<button (click)="onSave()">Save</button>
(click)
: is the target event name
onSave()
: is the template statement