+2

Standalone trong angular 14

Standalone trong Angular (>=v.14)

Tổng quan:

  • Standalone components là một dạng component được khai báo độc lập, không phụ thuộc việc khai báo trong NgModules như cách thông thường. Standalone components gồm components, directives hoặc pipes.
  • Standalone components không còn phụ thuộc Angular module, thay vì theo cách thông thường component được khai báo trong mảng declarations.

1. Standalone component

Tạo Standalone Component bằng cli:

  • ng g p search --standalone - tạo standalone pipe.
  • ng g d credit-card --standalone - tạo standalone directive.
  • ng g c login --standalone - tạo standalone component.
@Component({
  standalone: true,
  selector: 'photo-gallery',
  imports: [ImageGridComponent],
  template: `
    ... <image-grid [images]="imageList"></image-grid>
  `,
})
export class PhotoGalleryComponent {
  // component logic
}

2. Dependencies trong Standalone Component

Standalone Component sử dụng nhiều dependencies (components, directives, pipes, ... ), những đối tượng này không thuộc dạng standalone và phải import trực tiếp trong component hoặc cũng có thể import toàn bộ ngModule.

Dùng keyword import của @Component decorator. Ví dụ đoạn code sau đây:

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule], // [NgModule]
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

3. Using a Standalone Component

Standalone component được import trong NgModule.

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    LoginComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Các trường hợp sử dụng

  • Component không phụ thuộc, sử dụng độc lập vào NgModule.
  • Directives, Pipes ít sử dụng hoặc hạn chế sử dụng.
  • Dùng trong phát triển modules hoặc thư viện.
  • NOTE: Angular có thể dùng chạy với standalone component như là component root của ứng dụng thay vì ngModules thông thường.

4. Standalone components cho phát triển thư viện

Theo cách xử lý thông thường

@NgModule({
  imports: [ImageCarouselComponent, ImageSlideComponent],
  exports: [ImageCarouselComponent, ImageSlideComponent],
})
export class CarouselModule {}

để thay thế ngModule trong publish components dùng cấu trúc as const trong TypeScript

export const CAROUSEL_DIRECTIVES = [ImageCarouselComponent, ImageSlideComponent] as const;

(Tiếp tục cập nhật)

References:


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí