简体   繁体   中英

Different dashbard views for different roles in Angular application

I've an application having 6 user roles for now, it may increase in future and for each user role I've different dashboard view.

At present I've handled this scenario by identifying user role at login and then changing the dashboard view according to that user role(while keeping route same for each each role for eg '/dashboard').

I did so because changes weren't major and I only need to hide some part is one role and add in other role. Now because complexity is increasing it is becoming intractible to handle all dashbaords views in single typescript file.

Should I make different routes for all roles or would you suggest any different approach to handle this scenario more efficiently?

You can use dynamic component loader .

dashboard.component.ts adding some lines of code fro reference:

@Component({
    selector: 'dashboard',
    template: `
        <ng-template dashboardHost></ng-template>
    `
})
export class DashboardComponent {

    private _dashboard: DashboardItem;

    get dashboard(): DashboardItem {
        return this._dashboard;
    }
    @Input()
    set dashboard(dashboard:DashboardItem){
        if(this._dashboard != dashboard) {
            this._dashboard = dashboard;
            this.loadDashboard();
        }
    }

    @ViewChild(DashboardDirective) dashboardHost: DashboardDirective;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    }

    loadDashboard() {
        const dashboardItem = this.dashboard;

        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(dashboardItem.component);

        const viewContainerRef = this.dashboardHost.viewContainerRef;
        viewContainerRef.clear();
        viewContainerRef.createComponent(componentFactory);
    }
}

dashboard-item.ts

import {Type} from '@angular/core';

export class DashboardItem {
  constructor(public component: Type<any>, public data: any) {}
}

dashboard.directive.ts Create directive as:

import {Directive, ViewContainerRef} from '@angular/core';

@Directive({selector: '[dashboardHost]'})
export class DashboardDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

Uses:

<dashboard [dashboard]="Dashboard"></dashboard>

get Dashboard() {
    // add your logic here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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