AngularDart路由是否支持类似Angular 5的命名路由出口?
Great question! I’ve used named router outlets in Angular (TypeScript) too, and they’re super handy for precisely controlling where route components render in the DOM. Here’s a step-by-step breakdown of how to get this working in AngularDart:
1. Configure Routes with Named Outlets
First, define your routes and specify which outlet each component should target using the outlet parameter in your route config. For example:
import 'package:angular_router/angular_router.dart'; import 'home_component.dart'; import 'sidebar_component.dart'; import 'modal_component.dart'; final routes = [ Route( path: '/', component: HomeComponent, useAsDefault: true, ), Route( path: '/sidebar', component: SidebarComponent, outlet: 'sidebar', // Maps this route to the "sidebar" outlet ), Route( path: '/modal', component: ModalComponent, outlet: 'modal', // Maps this route to the "modal" outlet ), ];
2. Add Named Router Outlets to Your Template
Next, add <router-outlet> elements in your template, using the name attribute to match the outlet names from your route config. This tells AngularDart exactly where to render each component:
<div class="app-layout"> <!-- Default outlet (no name specified) --> <main class="main-content"> <router-outlet></router-outlet> </main> <!-- Named "sidebar" outlet --> <aside class="sidebar"> <router-outlet name="sidebar"></router-outlet> </aside> <!-- Named "modal" outlet --> <div class="modal-container"> <router-outlet name="modal"></router-outlet> </div> </div>
3. Navigate to Named Outlet Routes
To load a component into a specific named outlet, use the Router service’s navigate method and specify the outlet parameter. Here’s an example from a component:
import 'package:angular/angular.dart'; import 'package:angular_router/angular_router.dart'; import 'route_paths.dart'; @Component( selector: 'some-component', template: '<button (click)="openSidebar()">Open Sidebar</button>', ) class SomeComponent { final Router _router; SomeComponent(this._router); Future<void> openSidebar() async { await _router.navigate( RoutePaths.sidebar.toUrl(), // Your route path outlet: 'sidebar', // Target the named outlet ); } Future<void> openModal() async { await _router.navigate( RoutePaths.modal.toUrl(), outlet: 'modal', ); } }
Key Notes
- Version Compatibility: Make sure you’re using a recent version of AngularDart (v6+ should support named outlets fully).
- Case Sensitivity: The outlet name in your route config must exactly match the
nameattribute in your<router-outlet>(case-sensitive!). - Multiple Active Outlets: You can have multiple named outlets active at the same time—just navigate to each route with their respective outlet parameters.
内容的提问来源于stack exchange,提问作者user1026498

