get URL parameter ActivatedRoute Angular

Issue

In my application for me to know that there is a parameter in my navigation route, I need to configure this route.

I have a component that should not be rendered in <router-outlet>.

This component is a panel that is in the corner of the screen for sending and receiving messages.

const routes: Routes = [
    {
        path: 'chatView/:contactId',
        component: ChatPanelComponent,
        resolve: {
            chat: ChatPanelService
        },
        canLoad: [GuardService],
    },
];

This way render my component in the center of the screen and I do not want this to happen.

In the module I configured so that when I accessed the route with "chatView /: contactId" I received a parameter to return the data of that contact when I loaded my application.

In my component:

    ngOnInit(): void {

        this._activatedRoute.params.subscribe((params: any) => {
            if (params.contactId){
               this._chatPanelService.getContato(params.contactId).then((contact) => {
                   this.toggleChat(contact);
               });
            }
        });
}

I would like to know if there is a way I can get this parameter without having to render this component in the <router-outlet> output, because this component is visible in the corner of the screen and thus renders the component twice in my application.

I need a way to get a parameter without rendering the component in the center of the app-root screen.

Solution

Lets assume this all happens in component “Dashboard” (or whatever your parent component is named),
You would create 2 routes, both pointing to “DashboardComponent”

const routes: Routes = [
{
    path: 'dashboard',
    component: DashboardComponent,
    resolve: {
        chat: ChatPanelService
    },
    canLoad: [GuardService],
},
{
    path: 'dashboard/:contactId',
    component: DashboardComponent,
    resolve: {
        chat: ChatPanelService
    },
    canLoad: [GuardService],
},
];

Then you would use your

this._activatedRoute.params.subscribe

code to read the contact id param

Answered By – ramden

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.