The angular brackets [] () {} what they bind and when to use which

15,427

Solution 1

All the above syntax can be found at this page of the Angular Documentation. You can read up more about Angular's Template Syntax on other blogs if you wish.

1) [class]="myclass"

The square brackets [...] represent the one-way property binding from the component logic (data) to the view (target element).

2) (ngModelChange)

This represents event binding, which allows the target to listen for certain events such as clicks and keypresses.

3) [(ngModel)]="mymodel2"

This represents two-way data binding, which combines the above two syntaxes. The property's data is displayed on the view, and at the same time, the property will be updated when the user makes any changes.

4) <ion-input placeholder="{{'INPUT_TEXT' | translate}}"/>

You are simply importing another component into your current component, and the placeholder attribute is assigned the value of the component property INPUT_TEXT through template interpolation.

The pipe operator (|) allows you to carry out transformation of the displayed value. Pipes accept an input and, return the respective transformed value

5) Similar to 4.

Solution 2

  • [class]="myclass" -> one way property binding, changes in variable class in the .ts will be reflected in the view. (Binding from typescript to HTML)
  • (ngModelChange)="mymodel" -> one way event binding, when a modelChange event occurs, do whatever is present in the expression, (one way binding from HTML to typescript)
  • [(ngModel)]="mymodel2" -> two way binding, changes in the variable mymode2 within typescript will be reflected in the view, if any change occurs in the view, like in an input, then that change will be reflected in typescript too.
  • <ion-input placeholder="{{'INPUT_TEXT' | translate}}"/> -> interploation, as an when the value of data within "{{}}" will change, the value of the placeholder attribute will be updated
  • <button>{{'BUTTON_TEXT'|translate}}</button> -> again, interpolation, just not bound to any property.
Share:
15,427
ir2pid
Author by

ir2pid

https://ir2pid.github.io

Updated on July 27, 2022

Comments

  • ir2pid
    ir2pid almost 2 years

    I see the brackets are used for data binding but what's the difference?

    the below snippets are the ones I use frequently. But mostly taken as documented without understanding why.

    • [class]="myclass"
    • (ngModelChange)="mymodel"
    • [(ngModel)]="mymodel2"
    • <ion-input placeholder="{{'INPUT_TEXT' | translate}}"/>
    • <button>{{'BUTTON_TEXT'|translate}}</button>