What is the Angular template syntax?
Template is an HTML snippet that helps Angular render a dynamic view of its components in an Angular application. The template syntax helps guide us on how to control the user interface and user experience by coordinating data between the class and the template. There are designed attributes and elements for writing an angular template.
Directives
Directives are markers on a DOM element like an attribute or a CSS class. They tell the Angular HTML compiler to attach a specific behavior to any of the DOM elements.
There are two types of directives:
- attribute (
ngClass,ngStyle) - structural (
ngIF,ngFor)
Example using ngstyle
In the code below, the ngstyle attribute directive helps to set the background to blue.
<div [ngStyle]="{'background-color':'blue'}"></<div>
Example using ngclass
In the code below, the ngclass attribute directive helps set a false value for the class of text-success.
[ngClass]="{'text-success':false}"
Example using ngIF
In the following snippet, we use ngFor to investigate if a test is true or false.
<ng-container *ngFor="let result of checker Test.getValue();">
<div *ngIf="Test.getValue() == 'black'">Test is true</div>
<div *ngIf="Test.getValue() == 'white'">Test is false</div>
</ng-container>
Interpolation
Interpolation has a double braced syntax ({{ }}), and helps in making data rendering in the template more dynamic.
Example using ({{}})
Here, the string value of businessName is used to replace the variable when parsed in a double brace.
businessName = 'Melton';
<h2>New business: {{ businessName }}</h2>
Template statements
Template statements are methods used in HTML for responding to every possible user event in Angular. For example, we can use a template statement for form submission. The possibility of responding to users’ events speaks well of Angular unidirectional data flow form.
One example of using a template statement is shown below. Whenever the user clicks the Add-Bottle button, Angular calls up the addBottle() method into use. In this way, the template statement responds to the event triggered by the user.
<button (click)="addBottle()">Add Bottle</button>
Binding syntax
An image source, a button state, or data for a specific user can be made possible with the binding syntax. The data binding process helps ensure the application page is updated and current. For instance, [] can be used to parse a value into a target element.
Example using []
In the example below, the use of [] helps treat the string as a dynamic value and not a static value, while src is the name of the img property.
<img [src] ="originalImage">