This article takes you through routing in Angular and the use ofAngularrouting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "angular Tutorial"
1. Command to create a project
ng new ng-demo --skip-install
2. Create the required components
ng g component components/home ng g component components/news ng g component components/newscontent
3. Find app-routing.module.ts and configure routing
Introduce components
import { HomeComponent } from './components/home/home.component'; import { NewsComponent } from './components/news/news.component'; import { ProductComponent } from './components/product/product.component';
Configure routing
const routes: Routes = [ {path: 'home', component: HomeComponent}, {path: 'news', component: NewsComponent}, {path:'product', component:ProductComponent }, {path: '*', redirectTo: '/home', pathMatch: 'full' } ];
4. Find app.component .html root component template, configure router-outlet to display dynamically loaded routes
//匹配不到路由的时候加载的组件 或者跳转的路由 { path: '**', /*任意的路由*/ // component:HomeComponent redirectTo:'home' }
jump Transfer method, page jump or js jump
The url address of the question mark parameter is displayed as.../list-item?id=1
queryParams attribute is fixed
//js jump
//router is an instance of ActivatedRoute
import { Router } from '@angular/router'; . constructor(private router: Router) {} . this.router.navigate(['/newscontent'],{ queryParams:{ name:'laney', id:id }, skipLocationChange: true //可以不写,默认为false,设为true时路由跳转浏览器中的url会保持不变,传入的参数依然有效 });
How to get parameters
import { ActivatedRoute } from '@angular/router'; constructor(public route:ActivatedRoute) { } ngOnInit() { this.route.queryParams.subscribe((data)=>{ console.log(data); }) }
Path The URL address of the parameters is displayed as.../list-item/1
{{ item.name }} //js跳转 //router为ActivatedRoute的实例 this.router.navigate([’/list-item’, item.id]);
Path configuration:
{path: ‘list-item/:id’, component: ListItemComponent}
How to obtain parameters
this.route.params.subscribe( param => { this.id= param['id']; } )
1. Create component and introduce component
import { WelcomeComponent } from ‘./components/home/welcome/welcome.component’; import { SettingComponent } from ‘./components/home/setting/setting.component’;
2. Configure routing
{ path:'home', component:HomeComponent, children:[{ path:'welcome', component:WelcomeComponent },{ path:'setting', component:SettingComponent }, {path: '**', redirectTo: 'welcome'} ] },
3. Define router-outlet in parent component
Update For more programming related knowledge, please visit:programming video! !
The above is the detailed content of Detailed explanation of routing and its usage in Angular. For more information, please follow other related articles on the PHP Chinese website!