In Angular, how can one component to have multiple HTML templates? - javascript

I am developing an ecommerce application, and one major feature is that this app should have multiple themes. The total number of themes could be 100 or even more. However, these themes all have the same data (For example: all home page have same banner images, new product, feature product data.) .
I know I can use ng-template or TemplateRef to determine which piece of HTML should display. But since I have over 100 themes, both ng-template or TemplateRef methods will load a lot of extra files. So I think I need some sort of lazy load, when a component loads the data then lazy loads the correct HTML template. So how can I have this work?

Looks like it is possible, all our routes are handled by lazy loaded modules. This is our out-of-the-box route config:
const routes: Routes = [
{ path: '', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
While module lazy has this route config:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
]
While HomeComponent is taken from the declarations of module lazy.
Then define another module, called for example lazy-two with the same route config, and its own HomeComponent.
Finally, you can switch between the modules by using this code:
lazyLoad() {
const routes: Routes = [
{
path: '',
loadChildren: () => import('./lazy-two/lazy-two.module')
.then(m => m.LazyTwoModule)
}
];
this.router.resetConfig(routes);
this.router.navigateByUrl('/home');
}
This will lazy load module lazy-two and refresh the route to /home - you will see the component of the new module displayed.
I couldn't create a stackblitz, some errors occurred probably because of lazy loading. So I ran it locally on my machine and pushed the code to GitHub
EDIT I managed to make a StackBlitz

I recommend used ComponentFactoryResolver to create the components that you need to render.
this.templates = [
{
id: "template-1",
component: Template1,
},
{
id: "template-2",
component: Template2,
},
];
ngOnInit() {
this.templates.forEach((element) => {
this.containerReference.createComponent(
this.factoryResolver.resolveComponentFactory(element.component)
);
});
}
in the .html you should have
<ng-container #containerReference><ng-container>

what about using the same component and styling it different when you select the template?

Related

Angular Lazy Loading Modules and entryComponents error

I'm lazy loading an angular module and while trying to open my DatesModal I'm getting this error:
No component factory found for DatesModal. Did you add it to #NgModule.entryComponents?
My lazyModule looks like this:
declarations: [DatesModal]
entryComponents: [DatesModal]
Im definitely adding the DatesModal in the entryComponents array of the lazyModule. Anyone got any idea what I could be missing here?
Please let me know if you need more info to answer this question.
It looks like you want to get/import this module in other modules, however this module is not visible to others. Try to export your module:
exports: [DatesModal]
UPDATE:
As Angular docs says:
For production apps you want to load the smallest code possible. The
code should contain only the classes that you actually need and
exclude components that are never used. For this reason, the Angular
compiler only generates code for components which are reachable from
the entryComponents; This means that adding more references to
#NgModule.declarations does not imply that they will necessarily be
included in the final bundle.
If a component isn't an entry component and isn't found in a template,
the tree shaker will throw it away. So, it's best to add only the
components that are truly entry components to help keep your app as
trim as possible.
To make your module to be lzay loaded, you need to do in routes:
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module').then(mod => mod.CustomersModule)
},
{
path: 'orders',
loadChildren: () => import('./orders/orders.module').then(mod => mod.OrdersModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
Read this docs about how to make your modules to be lazy loaded.
Have you used any third-party library (or yourself) to dynamic create this component in lazy-load module?
If so, you need to add this component in the AppModule's (or up-level non-lazy-load module) entrycomponents.
More detail you can see this issue

Angular 6: How to use multiple loadChildren with same route?

I have something like:
const routes: Routes = [
{
path: ':path', component: SiteRoot, children: [
{ path: '', loadChildren: '../modules/maple/template.module#TemplateModule' }
]
}
];
I wish to use this :path url to match multiple module dynamically. each module have there own internal Route.
Is there any way I can achieve this?
I tried ViewContainerRef with ResolveComponentFactory but it does not work with module only component. Event with NgModuleFactoryLoader, Routes cannot be applied.
EDIT, to make everything clear:
What I am trying to achieve is to have different module display on same route path. For example user can see user dashboard at "home" path, and admin can see admin dashboard at "home" path as well.
This feature is defined by business logic, so, I cannot change admin dashboard to another url
I think you are trying to create your routing module incorrectly. Anyway, you should write why you need this. I'll try to answer. Every module should have it's own path, so routing module should be strict and static. If you trying it for security, use guards and hide item from menu component.
If you need URLs like this: "/username1/profile", "/username2/profile" you can simply use code like yours, or use lazy loading. create routing file for parent module:
{ path: ':username', loadChildren: '../users/user.module#UserModule' }
Than create routing file for child module:
{ path: '', loadChildren: 'UserComponent', children: [
{ path: '', redirectTo: 'profile' },
{ path: 'profile', component: ProfileComponent}
]
}
Updated By your case:
by your case you can change your HTML file. For example in app.component.html if your code is:
<div>
<router-outlet></router-outlet>
</div>
You can change it with:
<div *ngIf="isLoggedIn | async">
<admin-panel></admin-panel>
</div>
<div *ngIf="(!isLoggedIn | async)">
<router-outlet></router-outlet>
</div>

Angular feature routing module - Child component not loaded

I have a feature module that I load in the AppModule, the AppRoutingModule looks like
const appRoutes: Routes = [
...
{
path: 'move-request/:id',
loadChildren: 'app/modules/move_requests/move_requests.module#MoveRequestModule'
},
...
];
And the configuration of routing for the feature module looks like
const moveRequestRoutes: Routes = [
{
path: '',
component: MoveRequestFormComponent,
data: {title: 'Move Request'}
},
{
path: 'move-request-success',
component: RequestSuccessComponent,
data: {title: 'Move request success'}
},
];
I would like to navigate to MoveRequestFormComponent as the default component when move-request/:id is routed to, this works fine, but when I call
this.router.navigate(['/move-request-success', {}]);
In MoveRequestFormComponent after some response from the server, I get
zone.js:665 Unhandled Promise rejection: Cannot match any routes. URL Segment: 'move-request-success' ; Zone: <root> ;
This configuration was working before I switched to Angular 6, Is it because of the change in the AppModule, where I have excluded this feature module as an import?
Any assistance on what I am missing would be much appreciated. As I have also tried with having a third component which will be the default component and uses the router-outlet to render the children and have a children property on this route to have as children
{
path: '',
component: MoveRequestFormComponent,
data: {title: 'Move Request'}
},
{
path: 'move-request-success',
component: RequestSuccessComponent,
data: {title: 'Move request success'}
},
But that also did not work, it stayed on the MoveRequestFormComponent, when 'move-request-success' was navigated to.Or maybe I should change the approach?
You don't have to import the feature module in AppModule as it is lazily-loaded. When you navigate to move-request/:id/move-request-success, the path matches the default route with path:'', and then it will look for and children of that route. You should add pathMatch:'full' to the first route, which is the default in this case. Since the mentioned route matches the first route and is unable to find and match any children, it is showing the error.
this.router.navigate(['/move-request-success', {}]);. If you add a / to a route this means you use absolute path from root. Have you tried without / ?
EDIT:
I think I see your problem. You navigate to a module with multiple components, which means after lazy loading the router configuration from the loaded module is used. This means
move-request/:id
Is the root of your module and every subroute needs to include the modules root in the url:
Your route should be move-request/:id/move-request-success
Urls in lazy loaded modules are:
module root (in your case move-request/:id) + configured route of the specific component (in your case move-request-success)

Vue with dynamic routes and components

Trying to build a test app to see if Vue is a suitable replacment for our AngularJS app. Trying to learn Vue at the same time.
After the user logs in we fetch some roles for that user. Base off those roles is how the menu gets built.
User1 { Role1, Role2, Role3}
In theory
User2 {Role1, Role3}
So Role1 would have a path of /start/page1 and page1 (component) and two child components.
Same with Role2 path of /start/page2 and page2 would have components on it.
I don't really want to build the routes until I know which roles the user has.
I'm using quasar-framework.org and using the menu slide out. Trying to create a menu on the fly. Seems like I need the components to already be imported?
I'm able to build the menu by looping through the roles and setting up a list of menus.
Trying to build the routes on the fly using this.$router.addRoutes(newRoute);
To do that I need the component to already be imported.
The Quasar way is load the components on the fly I guess.
In router.js
function loadPage (component) {
return () => import(`../../pages/${component}.vue`)
}
I can't seem to use that function in a method section.
Is this possible in Vue?
Take a look at vue-router lazy loading documentation and Quasar lazy loading documentation
You can't do it in a method, but if the user permission don't match the route permissions the component is never loaded, which is basically what you want.
Example
const routes = [
{
path: '/some-page-protected',
component: () => import('pages/SomePage'),
meta: {role: 'admin'}
}
]
Or
const SomePage = () => ('pages/SomePage')
const routes = [
{
path: '/some-page-protected',
component: SomePage,
meta: {role: 'admin'}
}
]

Async components Vue 2

I'm trying to use async components. Here is my configuration:
Vue 2 using Single File Component approach
Webpack 2
Vue Router
The app is pretty basic, I have an "everyone" section contained in App and an "admin" section contained in Admin. I would like to load the component and all the .js related to the Admin if and only if I'm visiting the corresponding route.
After reading the vue-router docs on Lazy Loading, and the one of Vue2 on async components, I'm still not sure how to do that especially with the Single File Component approach.
Here is what I did for the moment but I don't know if it is ok since in the documentation of Vue2 they said :
Vue.component(
'async-webpack-example',
() => import('./my-async-component')
)
Also what do I have to do with webpack so it creates a chunk of everything related to Admin so that adminChunk.jsis just loaded when reaching admin route ?
What is the syntax to make a single file component a async component ?
app.js
const Admin = resolve => {
// require.ensure is Webpack's special syntax for a code-split point.
require.ensure(['./components/admin/Admin.vue'], () => {
resolve(require('./components/admin/Admin.vue'))
})
};
const routes = [
{ path: '/', component: App },
{ path: '/admin', meta: { requiresAdmin: true }, component: Admin},
];
Admin.vue
<template>
<admin-menu></admin-menu>
<child></child>
</template>
<script>
import AdminMenu from './Admin-Menu.vue'
import Child from './child.vue
export default{
data () {
},
components: {
AdminMenu,
Child,
},
}
</script>
You can pass a third parameter to the require.ensure function with the name of the chunk.

Categories

Resources