- Bài viết này mình sẽ hướng dẫn mọi người cách CRUD trong Angular với 2 bảng trở lên
- Đầu tiên khởi tạo dự án Angular
- Tạo interface Product như sau:

- Category:

- Tạo file ProductService

- Chúng ta tạo lần lượt các component CreateProduct, UpdateProduct, ListProduct, DeleteProduct
- create-product.component.ts
import {Component, OnInit} from ‘@angular/core’;
import {FormControl, FormGroup} from ‘@angular/forms’;
import {Product} from ‘../../model/product’;
import {ProductService}
from ‘../../service/product.service’;
import {Category} from ‘../../model/category’;
import {CategoryService}
from ‘../../service/category.service’;
@Component({
selector: ‘app-create-product’,
templateUrl: ‘./create-product.component.html’,
styleUrls: [‘./create-product.component.css’]
})
export
class CreateProductComponent
implements OnInit {
productForm: FormGroup = new FormGroup({
name: new FormControl(”),
category: new FormControl(”)
});
categoryList: Category[] = [];
constructor(private productService: ProductService,
private categoryService: CategoryService) {
}
ngOnInit() {
this.getCategories();
}
addProduct() {
const product: Product = {
name: this.productForm.value.name,
category: {
id: this.productForm.value.category
}
};
this.productService.createProduct(product).subscribe(() => {
alert(‘success’);
this.productForm.reset();
}, () => {
});
}
getCategories() {
this.categoryService.listCategory().subscribe((result) => {
this.categoryList = result;
});
}
}
- create-product.component.html
<div class=”text-center”>
<h2>Tạo mới sản phẩm</h2>
</div>
<form [formGroup]=”productForm” (ngSubmit)=”addProduct()”>
<label class=”col”>
Tên sản phẩm:
<input type=”text” formControlName=”name” class=”form-control”>
</label>
<label class=”col”>
<label for=”category”>Danh mục:</label>
<select class=”custom-select
custom-select-sm” id=”category” formControlName=”category”>
<option *ngFor=”let category of categoryList” [value]=”category.id”>{{category.name}}</option>
</select>
</label>
<div class=”col”>
<button class=”btn btn-info” type=”submit”>Tạo mới</button>
</div>
</form>
- Và đây là giao diện và kết quả sau khi tạo mới

Sau đó chúng ta vào trong db để kiểm tra
