Angular学习之聊聊独立组件(Standalone Component)

 3579

本篇文章带大家继续angular的学习,简单了解一下Angular中的独立组件(Standalone Component),希望对大家有所帮助!


Angular学习之聊聊独立组件(Standalone Component)


Angular 14一项令人兴奋的特性就是Angular的独立组件(Standalone Component)终于来了。

在Angular 14中, 开发者可以尝试使用独立组件开发各种组件,但是值得注意的是Angular独立组件的API仍然没有稳定下,将来可能存在一些破坏性更新,所以不推荐在生产环境中使用。


基本使用

angular.io/guide/stand…

standalone 是 Angular14 推出的新特性。

它可以让你的 根模块 AppModule 不至于那么臃肿

所有的 component / pipe / directive 都在被使用的时候 在对应的组件引入就好了

举个例子 这是之前的写法 我们声明一个 Footer 组件

然后在使用的 Module 中导入这个组件

  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4.   selector: 'app-footer',
  5.   template: ` <footer class="dark:bg-gray-800 dark:text-gray-50">Footer</footer> `,
  6. })
  7. export class FooterComponent {}
  1. import { NgModule } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { FooterComponent } from './footer.component';
  4.  
  5. @NgModule({
  6.   declarations: [HomeComponent, FooterComponent],
  7.   exports: [],
  8.   imports: [CommonModule],
  9. })
  10. export class AppModuleModule {}

这种写法导致我们始终无法摆脱 NgModule

但其实我们的意图就是在 AppComponent 中使用 FooterComponent

换成 React 中的写法 其实会更便于管理和理解

用上我们的新特性 standalone

Footer 组件就改造成这样

  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4.   selector: 'app-footer',
  5.   // 将该组件声明成独立组件
  6.   standalone: true,
  7.   template: ` <footer class="dark:bg-gray-800 dark:text-gray-50">Footer</footer> `,
  8. })
  9. export class FooterComponent {}

然后比如在 Home 页面 我们就可以这样使用

  1. import { Component } from '@angular/core';
  2.  
  3. import { FooterComponent } from '@components/footer/footer.component';
  4.  
  5. @Component({
  6.   selector: 'app-home',
  7.   standalone: true,
  8.   // 声明需要使用的 component / pipe / directive 但是它们也必须都是独立组件
  9.   imports: [FooterComponent],
  10.   template: `<app-footer></app-footer>`,
  11. })
  12. export class WelcomeComponent {}

独立组件可以直接用于懒加载 本来我们必须借助 NgModule 来实现

  1. import { NgModule } from '@angular/core';
  2. import { RouterModule, Routes } from '@angular/router';
  3.  
  4. import { CustomPreloadingStrategy } from '@views/basic-syntax/router/customPreloadingStrategy';
  5.  
  6. const routes: Routes = [
  7.   {
  8.     path: 'home',
  9.     // 之前想要实现懒加载 这里必须是一个NgModule 现在使用独立组件也可以 并且更加简洁
  10.     loadComponent: () => import('@views/home/home.component').then((mod) => mod.HomeComponent),
  11.   },
  12. ];
  13.  
  14. @NgModule({
  15.   imports: [RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })],
  16.   exports: [RouterModule],
  17. })
  18. export class AppRoutingModule {}


本文网址:https://www.zztuku.com/detail-13608.html
站长图库 - Angular学习之聊聊独立组件(Standalone Component)
申明:本文转载于《掘金社区》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐