- vừa được xem lúc

Sử dụng directives trong angular 13

0 0 21

Người đăng: Gấu con

Theo Viblo Asia

Directives là các lớp định nghĩa hành vi đến các thành phần trong các ứng dụng angular. Sử dụng built-in directives để quản lý forms, danh sách, styles và những gì người dùng nhìn thấy.

Built-in structural directives

Structural directives chịu trách nhiệm về bố cục HTML. Chúng định hình hoặc định hình lại cấu trúc của DOM, thường bằng cách thêm, xóa và thao tác các phần tử chính mà chúng được gắn vào.
DOM Javascript là viết tắt của chữ Document Object Model, dịch tạm ra là mô hình các đối tượng trong tài liệu HTML. Thông qua mô hình DOM ta có thể truy xuất đến các thẻ HTML một cách dễ dàng.

Sử dụng NgIf

Chúng ta có thể thêm hoặc xóa một phần tử bằng cách áp dụng directive NgIf cho một thành phần chính.
Khi NgIf là false, Angular sẽ xóa một thành phần và thành phần con của nó khỏi DOM. Angular sau đó loại bỏ các thành phần của chúng, giúp giải phóng bộ nhớ và tài nguyên.
Để thêm hoặc bớt một phần tử, hãy gắn *ngIf với một biểu thức điều kiện chẳng hạn như isActive, ví dụ:
Tạo một ItemDetailComponent với command sau:

ng g c ItemDetail

Tiếp theo cập nhật code component template tương ứng:
src/app/item-detail.component.html

<p>item-detail works!</p>

src/app/app.component.html
Thêm selector app-item-detail của ItemDetailComponent vào file app.component.html

<app-item-detail *ngIf="isActive" [item]="item"></app-item-detail>

src/app/app.component.ts
Cập nhật code như sau:

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})
export class AppComponent { isActive: boolean = true;
}

Chạy ứng dụng và xem kết quả:

item-detail works!

Khi biểu thức isActive trả về giá trị true, NgIf sẽ thêm ItemDetailComponent vào DOM.
Khi biểu thức isActive là false, NgIf sẽ xóa ItemDetailComponent khỏi DOM và loại bỏ component cũng như tất cả các thành phần con của nó.

Guarding against null
Theo mặc định, NgIf ngăn hiển thị một phần tử được liên kết với giá trị null.

Hãy cập nhật code như bên dưới:
src/app/app.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})
export class AppComponent { currentCustomer = {'name': 'yamada'}; nullCustomer = null;
} 

src/app/app.component.html

<div *ngIf="currentCustomer">Hello, {{currentCustomer.name}}</div>

Trong ví dụ trên, currentCustomer được hiển thị, bởi vì có một giá trị currentCustomer.
Output:

Hello, yamada

Tuy nhiên, nếu thuộc tính là null, Angular sẽ không hiển thị , ví dụ sau, Angular sẽ không hiển thị nullCustomer bởi vì nó là null:
src/app/app.component.html:

<div *ngIf="nullCustomer">Hello, <span>{{nullCustomer}}</span></div>

Sử dụng NgFor

Sử dụng NgFor để hiển thị danh sách các mục. Hãy xem Ví dụ sau:
Hãy thêm code vào các file tương ứng trong app.component như bên dưới:
src/app/app.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})
export class AppComponent { items = ['Angular', 'Javascript', 'PHP', 'Laravel'];
} 

src/app/app.component.html:

<div *ngFor="let item of items">{{item}}</div>

Output:

Angular
Javascript
PHP
Laravel

Repeating a component view
Để lặp lại một thành phần component, chúng ta sẽ sử dụng *ngFor đến selector. Ví dụ bên dưới chúng ta sử dụng với selector <app-item-detail>.
src/app/app.component.html:

<div *ngFor="let item of items">{{item}}</div>
<app-item-detail *ngFor="let item of items"></app-item-detail>

Output:

Angular
Javascript
PHP
Laravel
item-detail works! item-detail works! item-detail works! item-detail works!

Getting the index of *ngFor
Trong *ngFor, thêm dấu chấm phẩy và let i = index . Ví dụ sau lấy index trong một biến có tên là i và hiển thị nó với mỗi item tương ứng trong .
src/app/app.component.html

<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item}}</div>

Output:

1 - Angular
2 - Javascript
3 - PHP
4 - Laravel

Sử dụng NgSwitch

Giống như câu lệnh switch trong JavaScript, NgSwitch hiển thị một phần tử trong số một số phần tử có thể có, dựa trên điều kiện chuyển đổi. Angular chỉ đặt phần tử đã chọn vào DOM.
NgSwitch là một bộ ba chỉ thị:NgSwitch, NgSwitchCase, NgSwitchDefault. Hãy xem ví dụ sau:
src/app/app.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})
export class AppComponent { source: string = 'language'; changeSource(newSource: string): void { this.source = newSource; }
} 

src/app/app.component.html

<div class="container"> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1" (change)="changeSource('Angular')"> <label class="form-check-label" for="flexRadioDefault1">Angular</label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault2" (change)="changeSource('Javascript')"> <label class="form-check-label" for="flexRadioDefault2">Javascript</label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault3" (change)="changeSource('PHP')"> <label class="form-check-label" for="flexRadioDefault3">PHP</label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault4" (change)="changeSource('Laravel')"> <label class="form-check-label" for="flexRadioDefault4">Laravel</label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault5" checked (change)="changeSource('language')"> <label class="form-check-label" for="flexRadioDefault5">other language</label> </div> <div [ngSwitch]="source"> <div *ngSwitchCase="'Angular'">Learn Angular</div> <div *ngSwitchCase="'Javascript'">Learn Javascript</div> <div *ngSwitchCase="'PHP'">Learn PHP</div> <div *ngSwitchCase="'Laravel'">Learn Laravel</div> <!-- . . . --> <div *ngSwitchDefault>Learn other language</div> </div>
</div>

Output:
Khi bạn thay đổi giá trị radio button, thì nội dung hiển thị cũng thay đổi tương ứng:

Built-in attribute directives

Attribute directives lắng nghe và sửa đổi hành vi của các thành phần HTML, attributes, properties và components. Các chỉ thị thuộc tính phổ biến nhất như sau:

COMMON DIRECTIVES DETAILS
NgClass Adds and removes a set of CSS classes.
NgStyle Adds and removes a set of HTML styles.
NgModel Adds two-way data binding to an HTML form element.

Sử dụng NgClass

Trên phần tử bạn muốn style, hãy thêm [ngClass] và đặt nó bằng một biểu thức. Trong trường hợp này, isSpecial là một boolean được đặt thành true trong app.component.ts.
isSpecialtrue nên ngClass sẽ thêm class special vào trong thẻ <div>.
src/app/app.component.html

<!-- toggle the "special" class on/off with a property -->
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>

Sử dụng NgClass với một method
Các bạn hãy theo dõi ví dụ bên dưới để hiểu hơn nhé:
src/app/app.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})
export class AppComponent { canSave: boolean = true; isUnchanged: boolean = true; isSpecial: boolean = true; currentClasses: Record<string, boolean> = {}; ngOnInit() { this.setCurrentClasses(); } setCurrentClasses() { // CSS classes: added/removed per current state of component properties this.currentClasses = { saveable: this.canSave, modified: !this.isUnchanged, special: this.isSpecial }; }
}

src/app/app.component.html

<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>

Output:

Sử dụng NgStyle

Các bạn hãy theo dõi ví dụ bên dưới để hiểu hơn nhé:
src/app/app.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})
export class AppComponent { canSave: boolean = true; isUnchanged: boolean = true; isSpecial: boolean = true; currentStyles: Record<string, string> = {}; ngOnInit() { this.setCurrentStyles(); } setCurrentStyles() { // CSS styles: set per current state of component properties this.currentStyles = { 'font-style': this.canSave ? 'italic' : 'normal', 'font-weight': !this.isUnchanged ? 'bold' : 'normal', 'font-size': this.isSpecial ? '24px' : '12px' }; }
}

src/app/app.component.html

<div [ngStyle]="currentStyles"> This div is initially italic, normal weight, and extra large (24px). </div>

Output:

Sử dụng ngModel

Sử dụng NgModel directive để hiển thị thuộc tính dữ liệu và cập nhật thuộc tính đó khi người dùng thực hiện thay đổi.
Các bạn hãy theo dõi ví dụ bên dưới để hiểu hơn nhé:
Để sử dụng NgModel, bạn phải import FormsModule và thêm nó vào danh sách imports của NgModule.
src/app/app.module.ts (FormsModule import)

import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular
/* . . . */
@NgModule({ /* . . . */ imports: [ BrowserModule, FormsModule // <--- import into the NgModule ], /* . . . */
})
export class AppModule { }

src/app/app.component.ts

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']
})
export class AppComponent { currentItem = {'name': 'yamaguchi'} setUppercaseName(name: string) { this.currentItem.name = name.toUpperCase(); }
}

src/app/app.component.html

<div class="container"> <fieldset><h4>NgModel examples</h4> <p>Current item name: {{currentItem.name}}</p> <p> <label for="example-ngModel">[(ngModel)]:</label> <input [(ngModel)]="currentItem.name" id="example-ngModel"> </p> <p> <label for="example-change">(ngModelChange)="...name=$event":</label> <input [ngModel]="currentItem.name" (ngModelChange)="currentItem.name=$event" id="example-change"> </p> <p> <label for="example-uppercase">(ngModelChange)="setUppercaseName($event)" <input [ngModel]="currentItem.name" (ngModelChange)="setUppercaseName($event)" id="example-uppercase"> </label> </p> </fieldset>
</div>

Output:

Bình luận

Bài viết tương tự

- vừa được xem lúc

Route in Angular JS

Router là một module được đặt tại @angular/router, cung cấp cho ứng dụng Angluar của chúng ta khả năng điều hướng và hiển thị nội dung phù hợp với địa chỉ URL. Với các ứng dụng web thông thường, việc điều hướng theo URL thường sẽ do phía server đảm nhiệm, giống như hình ảnh dưới đây là ví dụ với Rai

0 0 84

- vừa được xem lúc

Có gì mới trong Angular 11

Phiên bản Angular 11.0.0 được phát hành vào tháng 11 năm 2020. Bản phát hành chính Angular 11 cung cấp các bản cập nhật trên toàn bộ nền tảng, bao gồm CLI và các components.

0 0 89

- vừa được xem lúc

Pipe trong Angular

Xin chào tất cả mọi người, bài viết này minh xin giới thiệu về Pipe trong Angular, rất mong được mọi người theo dõi. 1) Pipe trong Angular là gì. . .

0 0 113

- vừa được xem lúc

Angular Reactive Forms: Cách sử dụng FormArray

Trong bài viết này chúng ta sẽ tìm hiểu khi nào và cách sử dụng FormArray, cả trong Component và trong Template, ngoài ra chúng ta sẽ xem cách để custom validation cho nó. Vì sao chúng ta cần sử dụng FormArray.

0 0 92

- vừa được xem lúc

RxJS và Reactive Programming

1 - Stream. Streams are a sequence of values over time.

0 0 340

- vừa được xem lúc

Mapping class Java với Angular Typescript model – Chưa bao giờ dễ đến thế

Xin chào mọi người hôm nay mình giới thiệu một loại đồ chơi cực xịn cực hay ho luôn, đây là một thư viện giúp cho mọi người tạo ra 1 class Typescript trong dự án Frontend ở đây mình lấy ví dụ là Angul

0 0 81