how to add [routerLink] from component?

19,052

Solution 1

Have you tried something like this....

onBtnActionClickedV(event) {
   this.router.navigate(['/parent/detail']);
    }

and make sure you import router i.e.

import { Router }          from '@angular/router';

Solution 2

To add routerLink into the component, We can achieve it in two way:-

One method is of using

this.router.navigate([url]); // Bind the url in Array

Another method is of using

this.router.navigateByUrl(url); 

For your reference, I have created an example, in stackblitz which solves the above problems by making use of two ways.

Example:

https://stackblitz.com/edit/angular-routerlinks-from-component


enter image description here

Share:
19,052
angel
Author by

angel

Updated on June 17, 2022

Comments

  • angel
    angel almost 2 years

    My html call to this component

       <navbar [title]="'Recorridos'"
                [hasNavbarItems]="true"
                [itemsJsonFileName]="'recorrido-list-navbar-items.json'"
                (btnActionClicked)="onBtnActionClicked($event)"
                (btnFilterClicked)="onBtnFilterClicked($event)">
        </navbar>
    

    this is a dynamic component then in onBtnActionClicked($event) needs to redirect like

    <a [routerLink]="['/parent/detail', detail.detailId]">{{detail.detailId}}</a>
    

    but as you see this can't be added from html then in my component I could call the button click doing

    onBtnActionClickedV(event) {
    
            }
    

    in that function how can I redirect like routerLink does??