简体   繁体   English

创建可重用 Angular UI 组件的最佳方法

[英]Best approach to create reusable Angular UI Components

I want to use Angular 2+ to create reusable UI components.我想使用 Angular 2+ 来创建可重用的 UI 组件。 I have been checking material.angular.io, but there are certain things I need more specific, shall i say.我一直在检查 material.angular.io,但我需要更具体的某些内容,我要说。

Like I want to make something like a "Bootstrap panel" or I want to make a specific Material Card which is templated ie, I can re-use that component as I wish and the design remains consistent.就像我想制作“Bootstrap 面板”之类的东西,或者我想制作一个特定的模板化材质卡,即,我可以根据需要重新使用该组件,并且设计保持一致。 It has a heading, a body and a footer.它有一个标题、一个正文和一个页脚。 All parts can contain HTML.所有部分都可以包含 HTML。

I see ng-content as a way to achieve this (works similar to the old transclude in angularjs).我认为ng-content是实现这一目标的一种方式(工作方式类似于 angularjs 中的旧 transclude)。

Is using ng-content considered "best practice"?使用ng-content被视为“最佳实践”? What are the chances its use gets deprecated in the future?它的使用在未来被弃用的可能性有多大?

How does everyone create "templates" or "containers" or "layouts" which are code-reusable?每个人如何创建代码可重用的“模板”或“容器”或“布局”? So that the developers don't have to continue writing boilerplate div's?这样开发人员就不必继续编写样板 div 了?

What are the other options?其他选项是什么?

It really depends the usage that you are trying to give to those components.这实际上取决于您尝试为这些组件提供的用途。 If you are trying to reuse them inside ONE app ONLY, then I create a component inside a folder called shared/components .如果您只想在一个应用程序中重用它们,那么我会在名为shared/components的文件夹中创建一个shared/components Then I inject those components where I want to use them.然后我将这些组件注入到我想使用它们的地方。

If I'm creating a things that are part of the shell (like navbar, sidebar etc) You can put them inside of the shared folder shared/shell then inject these components in the app.component.html如果我创建的东西是 shell 的一部分(如导航栏、侧边栏等),您可以将它们放在共享文件夹shared/shell然后将这些组件注入app.component.html

Now if you are trying to make shareable components that can be used in different apps, then you will have to create a library, then you can deploy it to NPM then consume it in any of your apps.现在,如果您正在尝试制作可在不同应用程序中使用的可共享组件,那么您必须创建一个库,然后您可以将其部署到 NPM,然后在您的任何应用程序中使用它。 There are multiple ways to do this.有多种方法可以做到这一点。

Well, you can create a Angular Library好吧,你可以创建一个Angular 库

In simple terms, this will be just like any other module (eg: sharedModule) .简单来说,这就像任何其他模块(例如:sharedModule)。 Create all UI components, pass the configurations and parameters as @Input() to it.创建所有 UI 组件,将配置和参数作为@Input()传递给它。 Once your module is ready, build and pack the library and host it in npm or keep it in a shared drive.模块准备就绪后,构建并打包库并将其托管在 npm 中或将其保存在共享驱动器中。

Later, when you create a new project, just npm install your library稍后,当您创建新项目时,只需npm install您的库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM