Chinmay
Chinmay

Reputation: 4882

Best approach to create reusable Angular UI Components

I want to use Angular 2+ to create reusable UI components. I have been checking material.angular.io, but there are certain things I need more specific, shall i say.

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. It has a heading, a body and a footer. All parts can contain HTML.

I see ng-content as a way to achieve this (works similar to the old transclude in angularjs).

Is using ng-content considered "best practice"? 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?

What are the other options?

Upvotes: 2

Views: 725

Answers (2)

Adrita Sharma
Adrita Sharma

Reputation: 22213

Well, you can create a Angular Library

In simple terms, this will be just like any other module (eg: sharedModule) . Create all UI components, pass the configurations and parameters as @Input() to it. Once your module is ready, build and pack the library and host it in npm or keep it in a shared drive.

Later, when you create a new project, just npm install your library

Upvotes: 2

Patricio Vargas
Patricio Vargas

Reputation: 5522

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. 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

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. There are multiple ways to do this.

Upvotes: 1

Related Questions