Angular Navigating to Secondary Route while Preserving Primary Route

☆樱花仙子☆ 提交于 2020-01-04 02:20:09

问题


I would like to navigate to a secondary route called modal without explicitly stating the primary route.

I've tried this in the component class:

onclick(){
    this.router.navigate([{ outlets: { foo: 'modal' } }], { relativeTo: this.route });
}

The above code seems to work. However, it navigates to /first(foo:modal) for a split second then it navigates to the root /.

What am I doing wrong?

It would be nice to do something like:

<a href="#" routerLink="/*(foo:modal)">Open Modal</a>

So that it matches any primary route.... Is this possible?


回答1:


You can set only the secondary segment by specifying the outlet { oultletName: url}

<a [routerLink]="[{outlets: { modal: 'edit/20']}}]">Edit</a>   
router.navigate([{outlets: { modal: 'edit/20'}}]);

or multiple segments:

<a [routerLink]="[{outlets: {primary: 'products', modal: 'edit/20']}}]">Edit</a> 
router.navigate([{outlets: {primary: 'products', modal: 'edit/20'}}]);



回答2:


The issue was href="#" on the achor tag that was causing the immediate redirect. Removing it resolved the issue.

To navigate to a secondary route regardless of the primary route:

<a routerLink="one" >Home</a>
<a routerLink="two" >Admin</a>
<a [routerLink]="[{ outlets: { foo: 'modal' } }]">open</a>
<a [routerLink]="[{ outlets: { foo: null } }]">close</a>

And if you want to navigate imperatively:

<a (click)="open()">Open</a>
<a (click)="close()">Close</a>

open() {
    this.router.navigate([{ outlets: { foo: 'modal' } }]);
}
close() {
    this.router.navigate([{ outlets: { foo: null } }]);
}


来源:https://stackoverflow.com/questions/45395788/angular-navigating-to-secondary-route-while-preserving-primary-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!