Tiep Phan · · 2 min read
JavaScript · Lập Trình · Lập Trình Angular · Programming · Web Development
Thử Nghiệm Với Angular 2 Phần 2: Built-in Directives NgIf, NgFor, NgSwitchCase
Xin chào các bạn, đây là bài học thứ hai trong series Thử Nghiệm Với Angular 2, trong bài trước mình đã giới thiệu về Angular 2 Component và Data Binding. Bài học này chúng ta sẽ tìm hiểu về built-in directives NgIf, NgFor, NgSwitchCase trong Angular.
Trong bài này chúng ta sẽ đi tìm hiểu các Directives được cung cấp bởi Angular 2 là NgIf, NgFor, NgSwitchCase qua các ví dụ tiếp nối từ bài học trước.
Lưu ý: để sử dụng các directives này, bạn cần import BrowserModule hoặc CommonModule
NgIf
Sử dụng khi muốn thêm hoặc xóa bỏ một phần tử khi render. Ví dụ: hiển thị thông báo lỗi khi người dùng nhập form chưa đúng.
Cú pháp:
<h2 *ngIf="printable">{{ message }}</h2>
Lưu ý: đừng quên dấu
*phía trướcngIfdirective
NgFor
Sử dụng khi muốn render một list các phần tử. Ví dụ: render list các bài học trong một series chẳng hạn.
Cú pháp:
<div *ngFor="let contact of contacts">
<h3>{{ contact.name }}</h3>
<div>
<img *ngIf="contact.avatar?.url" [src]="contact.avatar?.url" alt="Avatar of {{ contact.name }}">
</div>
</div>
Lưu ý: đừng quên dấu
*phía trướcngFordirective và sử dụng cấu trúclet ... of ...
NgSwitchCase
Sử dụng thay thế việc if nhiều lần, tương tự như switch-case trong JavaScript.
Cú pháp:
<div [ngSwitch]="conditionExpression">
<template [ngSwitchCase]="case1Exp">...</template>
<template ngSwitchCase="case2LiteralString">...</template>
<template ngSwitchDefault>...</template>
</div>
Hoặc:
<div [ngSwitch]="tabIndex">
<div *ngSwitchCase="1">
<div>
Tab content 1
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore, rerum.
</p>
</div>
<div *ngSwitchCase="2">
<div>
Tab content 2
</div>
<p>
Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.
</p>
</div>
<div *ngSwitchCase="3">
<div>
Tab content 3
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ducimus a sequi cupiditate accusantium vitae impedit eum illo voluptatem neque, nisi.
</p>
</div>
</div>
Lưu ý: không có dấu
*ở phía trướcngSwitchdirective. Thay vào đó, sử dụng property binding.Đặt dấu
*ở phía trướcngSwitchCasevàngSwitchDefault. Trường hợp sử dụng với thẻtemplatenhư ở ví dụ đầu tiên củangSwitchthì không.