Angular独立组件怎么使用


这篇文章主要介绍“Angular独立组件怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Angular独立组件怎么使用”文章能帮助大家解决问题。

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

基本使用

angular.io/guide/stand…

standalone 是 Angular14 推出的新特性。

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

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

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

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

import{&nbspponent}from'@angular/core';ponent({selector:'app-footer',template:`<footerclass="dark:bg-gray-800dark:text-gray-50">Footer</footer>`,})exportclassFooteponent{}
import{NgModule}from'@angular/core';import{&nbspmonModule}from'@angularmon';import{Footeponent}from'./footerponent';@NgModule({declarations:[Homponent,Footeponent],exports:[],imports:monModule],})exportclassAppModuleModule{}

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

但其实我们的意图就是在 Apponent 中使用 Footeponent

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

用上我们的新特性 standalone

Footer 组件就改造成这样

import{&nbspponent}from'@angular/core';ponent({selector:'app-footer',//将该组件声明成独立组件standalone:true,template:`<footerclass="dark:bg-gray-800dark:text-gray-50">Footer</footer>`,})exportclassFooteponent{}

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

import{&nbspponent}from'@angular/core';import{Footeponent}from'ponents/footer/footerponent';ponent({selector:'app-home',standalone:true,//声明需要使用的&nbspponent/pipe/directive但是它们也必须都是独立组件imports:[Footeponent],template:`<app-footer></app-footer>`,})exportclassWeponent{}

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

import{NgModule}from'@angular/core';import{RouterModule,Routes}from'@angular/router';import{CustomPreloadingStrategy}from'@views/basic-syntax/router/customPreloadingStrategy';constroutes:Routes=[{path:'home',//之前想要实现懒加载这里必须是一个NgModule现在使用独立组件也可以并且更加简洁loaponent:()=>import('@views/home/homeponent').then((mod)=>mod.Homponent),},];@NgModule({imports:[RouterModule.forRoot(routes,{preloadingStrategy:CustomPreloadingStrategy})],exports:[RouterModule],})exportclassAppRoutingModule{}

关于“Angular独立组件怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注主机评测网行业资讯频道,小编每天都会为大家更新不同的知识点。


上一篇:vue menu不刷新如何解决

下一篇:go是不是一种语言


Copyright © 2002-2019 测速网 https://www.inhv.cn/ 皖ICP备2023010105号 城市 地区 街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!
热门搜索