跳转法一

一、引入

  1. import {Router} from "@angular/router";

二、创建跳转事件

  1. //home.ts
  2. import {Router} from "@angular/router";
  3. export class HomeComponent implements OnInit {
  4. public id:string='22222'
  5. constructor(private router:Router) { }//这里要添加
  6. ngOnInit() {
  7. }
  8. handleClick(){
  9. this.router.navigate(['/detail'])
  10. }
  11. }

三、跳转事件传值

  1. handleClick(){
  2. this.router.navigate(['/detail',this.id])
  3. }

四、接收

  1. //detail.ts
  2. import { Component, OnInit } from '@angular/core';
  3. import {ActivatedRoute} from '@angular/router'
  4. @Component({
  5. selector: 'app-detail',
  6. templateUrl: './detail.component.html',
  7. styleUrls: ['./detail.component.css']
  8. })
  9. export class DetailComponent implements OnInit {
  10. constructor(public route:ActivatedRoute) { }
  11. p
  12. ngOnInit() {
  13. this.route.params.subscribe(res=>{
  14. console.log(res)
  15. })
  16. }
  17. }

跳转法二

一、引入

  1. //home.ts
  2. import {Router,NavigationExtras} from "@angular/router";

二、跳转事件

  1. export class HomeComponent implements OnInit {
  2. public id:string='22222'
  3. constructor(private router:Router) { }
  4. ngOnInit() {
  5. }
  6. handleClick(){
  7. let NavigationExtras:NavigationExtras={
  8. queryParams:{
  9. "id":this.id
  10. }
  11. }
  12. this.router.navigate(['/detail'],NavigationExtras)
  13. }
  14. }

三、接收

  1. //detail.ts
  2. import { Component, OnInit } from '@angular/core';
  3. import {ActivatedRoute} from '@angular/router'
  4. export class DetailComponent implements OnInit {
  5. constructor(public route:ActivatedRoute) { }
  6. ngOnInit() {
  7. this.route.queryParams.subscribe(res=>{
  8. console.log(res)
  9. })
  10. }
  11. }