I build auth
lib in my nx monorepo.
The auth
lib contains LoginComponent
(smart) and LoginFormComponent
(dumb).
And I load the lib as lazy by using loadChildren
to load auth.module
and inside this module I have a child route to the LoginComponent
which have LoginFormComponent
.
Inside the LoginFormComponent
I have text: "Login to my awesome app".
<h1>Login to my awesome app</h1>
<form...>
The problem is when I want to add another angular application and use this auth components and functionality.
So when I use the auth from the new application, I'm getting the text: "Login to my awesome app".
For the existing app the text should be: "Login to my awesome app".
And for new app should be: "Login to ng app".
I have only one auth
lib with one of login component.
So I looking for angular way to deal with such senario.
I was think about duplicate the component but it's not feel right. or to use i18n but not sure because it's for langs, or using forRoot
and pass the providers with the text? using tokens with inject?
What the ways I can do to change the text? How to handle this issue? is it solution to angular for this senario?
I can understand your situation. Here is what you should do. I am assuming that you have created a @shared/auth
lib under nx
monorepo. The auth
lib contains the LoginFormComponent
.
You should exploit ForRoot
and @Inject()
to achieve the same.
auth.module.ts
@NgModule({
// all imports etc
})
export class AuthModule {
static forRoot(appName: string): ModuleWithProviders<AuthModule> {
return {
ngModule: AuthModule,
providers: [
{ provide: APP_NAME, useValue: appName }
],
};
}
}
To avoid any circular dependency while importing APP_NAME
, create a file as
config.ts
export const APP_NAME = new InjectionToken<string>('APP_NAME_PARAM');
Lets go your LoginFormComponent
LoginFormComponent.component.ts
export class LoginFormComponent{
public appName: string;
constructor(@Inject(APP_NAME) clientAppName: string){
this.appName = clientAppName;
}
}
login.component.html
<h1>Login to {{appName}} app</h1>
Now, we are all set. Only thing left to do, is to use AuthModule
in our app.module.ts
app.module.ts
@NgModule({
imports: [
AuthModule.forRoot("Super Awesome")
]
})
export class AppModule
This can help you reuse the AuthModule
in other apps as well. You just need create a constant
file for each app library and then move Super Awesome
into that constant for better readability.
It may not be completely relevant but, you can check this article for more understanding of ForRoot and InjectionToken
I have extensively used it in my Nx monorepo projects. Its a standard way.