SweetAlert2 là một thư viện JavaScript mã nguồn mở được sử dụng để tạo các cửa sổ thông báo (alerts), thông báo cảnh báo (warnings), và hộp thoại xác nhận (confirmations) với giao diện đẹp mắt và tùy chỉnh cao. Với giao diện đẹp mắt, khả năng tùy chỉnh tốt, cùng với việc dễ tích hợp, SweetAlert2 vẫn tiếp tục là thư viện được nhiều lập trình viên tin dùng.
Trang chủ: https://www.npmjs.com/package/sweetalert2
Để tích hợp vào dự án Angular của mình bạn chỉ cần thực hiện 3 bước sau:
Bước 1: cài đặt NPM Package
npm install sweetalert2
Bước 2: Tại file angular.json thêm dòng "node_modules/sweetalert2/src/sweetalert2.scss" sau "src/styles.css"
....
....
....
"styles": [
"src/styles.css",
"node_modules/sweetalert2/src/sweetalert2.scss"
],
....
....
....
Mục đích của bước này là giúp dự án Angular load file css của Sweetalert2.
Bước 3: Sử dụng
Sau khi đã tích hợp xong từ 2 bước trên, giờ bạn có thể sử dụng tại các component của mình ví dụ:
File app.component.ts
import { Component, OnInit } from '@angular/core';
import Swal from 'sweetalert2';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
ngOnInit() {
}
simpleAlert() {
Swal.fire('Đơn giản!');
}
successAlert() {
Swal.fire('Hello', 'Success Alert', 'success');
}
confirmAlert() {
Swal.fire({
title: 'Are you sure?',
text: 'Bạn có chắc chắn xóa?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes.',
cancelButtonText: 'Cancel',
}).then((result) => {
if (result.value) {
} else if (result.dismiss === Swal.DismissReason.cancel) {
}
});
}
}
File app.component.html
<h1>OnDeBug.Net</h1>
<button (click)="simpleAlert()">simpleAlert</button>
<button (click)="successAlert()">successAlert</button>
<button (click)="confirmAlert()">simpleAlert</button>
Cuối cùng ta đươc kết quả sau: