ng 路由

作者: Daeeman | 来源:发表于2020-04-29 19:59 被阅读0次

基本用法 添加 AppRoutingModule

ng generate module app-routing --flat --module=app

app-routing.module.ts

import { NgModule }  from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FooComponent } from './foo/foo.component'
import { BarComponent } from './bar/bar.component'
const routes: Routes = [
    {
      path: 'foo',
      component: FooComponent
    },
    {
      path: 'bar',
      component: BarComponent
    }
    { path: '**', component:SwiperComponent},
    { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
]
@NgModule({
    imports: [
      RouterModule.forRoot(routes)
    ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

设置路由出口:

<h1>{{title}}</h1>
  <router-outlet></router-outlet>

设置导航链接:

<ul>
    <li>
      <a routerLink="/foo">Go Foo</a>
    </li>
    <li>
      <a routerLink="/bar">Go Foo</a>
    </li>
  </ul>

导航链接 routerLink

路由对象

  • path
    • 不能以 / 开头
  • component

默认路由:

{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },

动态路由匹配

动态路径配置:

{ path: 'detail/:id', component: HeroDetailComponent },

导航链接:

<a *ngFor="let hero of heroes"  [routerLinkActive]="['active']" class="col-1-4"
      routerLink="/detail/{{hero.id}}">

在组件中解析获取动态路径参数:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
@Component({
    selector: 'app-user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.css']
  })
export class UserComponent implements OnInit {
    constructor(
      private route: ActivatedRoute,
      private location: Location
    ) { }

    ngOnInit() {
      // const id = this.route.snapshot.paramMap.get('id')
      this.route.params.subscribe(item => {
        this.id =  item.id;
         console.log(item.id)
        this.getUser();
     });

    }
}

路由导航

后退:

this.location.back();
  • 导航链接 routerLink
  • 路由对象
  • 动态路由匹配
  • 路由导航

相关文章

  • ng 路由

    基本用法 添加 AppRoutingModule app-routing.module.ts 设置路由出口: 设置...

  • 面试知识6Angular(模拟面试)

    一:angular路由实现原理 ng-route:主要是通过$routeProvider(配置路由的映射)搭配ng...

  • Angular学习笔记(四)Angular Router 导航

    学习路由基本知识学习子路由、保护路由、辅助路由等 一、创建路由项目 使用 ng new xxx --routing...

  • 模拟面试中遇到的知识点

    1.AngularJS中路由实现的原理? 路由功能主要是 $routeProvider服务 与 ng-view 实...

  • Angular路由ui-router

    简介 angularJs自身提供路由ng-router,但是ng-router不是很好用,配置项零散,好比...

  • angular--路由

    生成一个跟angular路由相关的项目:ng new router --routing;生成组件:ng g com...

  • ng路由传参

    angular的路由传递参数一共有三种方式 固定参数、动态路由参数、查询参数三种叫法是本人习惯叫法 非官方 仅供...

  • angular-路由

    使用路由需遵循如下步骤: 1、导入路由模块 如果在运行ng new xxx命令时,没有选择路由选项,我们可以手动安...

  • angular7 cli命令创建组件

    创建页面的命令:ng g component [文件名称]命令.png创建结果.png 2.添加路由文件命令:ng...

  • 在ng-view视图中通过ng-include切换视图的小技巧

    AngularJS中URL路由特性有系列限制:你不能嵌套多个ng-view指令的实例,这使得他在ng-view作用...

网友评论

      本文标题:ng 路由

      本文链接:https://www.haomeiwen.com/subject/yjanwhtx.html