How does the order of the imports in angular works ? Why is not working with one order and...

Discussão em 'Angular' iniciado por Gregory Boutte, Agosto 26, 2025.

  1. I created a directive that allow me to change the routerLink of my links.

    I encountered an error where the routerLink was not updated in one component, but was correctly updated in an other.

    I found out that it was because I did not have the same import order in my components.

    For example my directive look like this :

    @Directive({
    selector: '[appMyRouter]',
    standalone: true,
    })
    export class MyRouterDirective extends RouterLink implements OnInit {

    public ngOnInit(): void {
    this.updateLink();
    }

    private updateLink(): void {
    const routerLink: string = this.urlTree?.toString() || '';

    this.routerLink = `/prefix/${routerLink}`;
    super.ngOnChanges();
    }
    }



    And my two component are like this

    @Component({
    selector: 'component1',
    standalone: true,
    imports: [CommonModule, MyRouterDirective, RouterLink],
    template: `
    <div>
    Component 1 (not working)
    <a appMyRouter routerLink="page1">Link 1</a>
    </div>
    `,
    })
    export class Component1 {}


    @Component({
    selector: 'component2',
    standalone: true,
    imports: [CommonModule, RouterLink, MyRouterDirective],
    template: `
    <div>
    Component 2 (working)
    <a appMyRouter routerLink="page1">Link 2</a>
    </div>
    `,
    })
    export class Component2 {}


    I also made a stackblitz with all the previous file

    The only thing changing is the order of the imports, but in one case it's not working.

    I have multiple questions.

    1. Is there a simple way to detect this kind of error, because there was no warking or compilation error, just was not working. So if I did not test it I could have not notice it.
    2. What the explanation behind this ? / Is it an intended behavior ?
    3. Is it possible to directly import the RouterLink inside my directive ?

    Continue reading...

Compartilhe esta Página