首頁  >  文章  >  web前端  >  Angular學習之聊聊獨立組件(Standalone Component)

Angular學習之聊聊獨立組件(Standalone Component)

青灯夜游
青灯夜游轉載
2022-12-19 19:24:472969瀏覽

這篇文章帶大家繼續angular的學習,簡單了解一下Angular中的獨立元件(Standalone Component),希望對大家有幫助!

Angular學習之聊聊獨立組件(Standalone Component)

Angular 14一項令人興奮的特性就是Angular的獨立元件(Standalone Component)終於來了。 【相關教學推薦:《angular教學》】

在Angular 14中,開發者可以嘗試使用獨立元件開發各種元件,但是值得注意的是Angular獨立元件的API仍然沒有穩定下,將來可能存在一些破壞性更新,所以不建議在生產環境中使用。

基本上使用

angular.io/guide/stand…

standalone 是Angular14 推出的新特性。

它可以讓你的根模組AppModule 不那麼臃腫

所有的component / pipe / directive 都在被使用的時候在對應的組件引入就好了

舉個例子這是之前的寫法我們聲明一個Footer 元件

然後在使用的Module 中導入這個元件

import { Component } from '@angular/core';

@Component({
  selector: 'app-footer',
  template: ` <footer class="dark:bg-gray-800 dark:text-gray-50">Footer</footer> `,
})
export class FooterComponent {}
import { NgModule } from &#39;@angular/core&#39;;
import { CommonModule } from &#39;@angular/common&#39;;
import { FooterComponent } from &#39;./footer.component&#39;;

@NgModule({
  declarations: [HomeComponent, FooterComponent],
  exports: [],
  imports: [CommonModule],
})
export class AppModuleModule {}

這種寫法導致我們始終無法擺脫NgModule

但其實我們的意圖就是在AppComponent 中使用FooterComponent

#換成React 中的寫法其實會更便於管理和理解

用上我們的新特性standalone

Footer 元件就改造成這樣

import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-footer&#39;,
  // 将该组件声明成独立组件
  standalone: true,
  template: ` <footer class="dark:bg-gray-800 dark:text-gray-50">Footer</footer> `,
})
export class FooterComponent {}

然後例如在Home 頁面我們就可以這樣使用

import { Component } from &#39;@angular/core&#39;;

import { FooterComponent } from &#39;@components/footer/footer.component&#39;;

@Component({
  selector: &#39;app-home&#39;,
  standalone: true,
  // 声明需要使用的 component / pipe / directive 但是它们也必须都是独立组件
  imports: [FooterComponent],
  template: `<app-footer></app-footer>`,
})
export class WelcomeComponent {}

獨立元件可以直接用於懶加載本來我們必須藉助NgModule 來實現

import { NgModule } from &#39;@angular/core&#39;;
import { RouterModule, Routes } from &#39;@angular/router&#39;;

import { CustomPreloadingStrategy } from &#39;@views/basic-syntax/router/customPreloadingStrategy&#39;;

const routes: Routes = [
  {
    path: &#39;home&#39;,
    // 之前想要实现懒加载 这里必须是一个NgModule 现在使用独立组件也可以 并且更加简洁
    loadComponent: () => import(&#39;@views/home/home.component&#39;).then((mod) => mod.HomeComponent),
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })],
  exports: [RouterModule],
})
export class AppRoutingModule {}

更多程式相關知識,請造訪:程式設計教學! !

以上是Angular學習之聊聊獨立組件(Standalone Component)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除