- Square Brackets
[]
(Property Binding):
- Used to bind a property of a DOM element to a component property. Example:
<!-- Binding the 'src' property of an image element to a component property 'imageUrl' -->
<img [src]="imageUrl">
- Parentheses
()
(Event Binding):
- Used to bind an event of a DOM element to a component method. Example:
<!-- Binding the 'click' event of a button to a component method 'handleClick' -->
<button (click)="handleClick()">
Click me
</button>
- Double Curly Braces
{{ }}
(Interpolation):
- Used to display the value of a component property in the template. Example:
<!-- Displaying the value of the 'name' property in a paragraph -->
<p>{{ name }}</p>
- Asterisk
*
(Structural Directives):
- Used to apply structural directives like
ngIf
,ngFor
, andngSwitch
in a more concise way. Example (ngFor):
<!-- Looping through an array and rendering items -->
<div *ngFor="let item of items">
{{ item }}
</div>
- Hash
#
(Template Reference Variables):
- Used to create a reference to an element or component in the template, which can be used in the component code. Example:
<!-- Creating a reference to an input element -->
<input #myInput>
- Round Brackets
()
inngFor
andngIf
:
- Used for local variables when using
ngFor
andngIf
structural directives. Example (ngFor):
<!-- Accessing the index of the current item in a loop -->
<div *ngFor="let item of items; let i = index">
Item {{ i }}: {{ item }}
</div>
- Pipe
|
(Pipe Operator):
- Used for data transformation in templates. It is used to format data before displaying it in the template. Example:
<!-- Formatting a date before displaying it -->
<p>{{ currentDate | date:'short' }}</p>
*ngIf
and*ngFor
(Structural Directives):
*ngIf
is used for conditionally rendering elements based on a condition. Example (ngIf):
<!-- Displaying a message only if 'showMessage' is true -->
<div *ngIf="showMessage">
This message will be displayed if showMessage is true.
</div>
*ngFor
is used for looping through a list of items and rendering elements accordingly. Example (ngFor):
<!-- Looping through an array of users and rendering their names -->
<div *ngFor="let user of users">
{{ user.name }}
</div>
[()]
(Two-Way Binding):
- Combines property binding and event binding to create a two-way data binding. It’s typically used with
ngModel
for form elements. Example:
<!-- Creating a two-way binding for an input element using ngModel -->
<input [(ngModel)]="myProperty">
[ngStyle]
and[ngClass]
:- Used for dynamically applying styles or classes to elements based on component properties or conditions.
<!-- Applying a dynamic text color based on the 'textColor' property --> <div [ngStyle]="{ color: textColor }"> This text will have a dynamic color. </div>
These examples should provide you with a more detailed understanding of how these expressions are used in Angular templates.
Leave a Reply