问题
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