Back to Angular

Built-in Directives

adev/src/content/examples/built-in-directives/src/app/app.component.html

22.1.0-next.12.6 KB
Original Source

Built-in Directives

Built-in attribute directives

NgModel (two-way) Binding

NgModel examples

Current item name: {{ currentItem.name }}

without NgModel:

[(ngModel)]:

(ngModelChange)="...name=$event":

(ngModelChange)="setUppercaseName($event)"


NgClass Binding

currentClasses is {{ currentClasses | json }}

This div is initially saveable, unchanged, and special.

  • saveable
  • modified:
  • special:

Refresh currentClasses This div should be {{ canSave ? '' : 'not' }} saveable, {{ isUnchanged ? 'unchanged' : 'modified' }} and {{ isSpecial ? '' : 'not' }} special after clicking "Refresh".

This div is special

Helpful study course

Study course


NgStyle Binding

This div is x-large or smaller.

[ngStyle] binding to currentStyles - CSS property names

currentStyles is {{ currentStyles | json }}

This div is initially italic, normal weight, and extra large (24px).

italic: |normal: |xlarge: Refresh currentStyles

This div should be {{ canSave ? 'italic' : 'plain' }}, {{ isUnchanged ? 'normal weight' : 'bold' }} and, {{ isSpecial ? 'extra large' : 'normal size' }} after clicking "Refresh".


Built-in structural directives

NgIf Binding

If isActive is true, app-item-detail will render:

Toggle app-item-detail

If currentCustomer isn't null, say hello to Laura:

Hello, {{ currentCustomer.name }}

nullCustomer is null by default. NgIf guards against null. Give it a value to show it:

Hello, {{ nullCustomer }} Give nullCustomer a value

NgIf binding with template (no *)

Add {{ currentItem.name }} with template


Show/hide vs. NgIf

Show with class

Hide with class

ItemDetail is in the DOM but hidden

Show with style

Hide with style


NgFor Binding

{{ item.name }}

*ngFor with ItemDetailComponent element

*ngFor with index

with semi-colon separator

{{ i + 1 }} - {{ item.name }}

with comma separator

{{ i + 1 }} - {{ item.name }}

*ngFor trackBy

Reset itemsChange idsClear counts

without trackBy

({{ item.id }}) {{ item.name }}

Item DOM elements change #{{ itemsNoTrackByCount }} without trackBy

with trackBy

({{ item.id }}) {{ item.name }}

Item DOM elements change #{{ itemsWithTrackByCount }} with trackBy

with trackBy and semi-colon separator

({{ item.id }}) {{ item.name }}

with trackBy and comma separator

({{ item.id }}) {{ item.name }}

with trackBy and space separator

({{ item.id }}) {{ item.name }}

with generic trackById function

({{ item.id }}) {{ item.name }}


NgSwitch Binding

Pick your favorite item

{{ i.name }}

Are you as bright as {{ currentItem.name }}?