第一种
html
<!-- sss?aid=1 -->
<ul>
<li *ngFor="let item of newsList; let key = index;">
<a [routerLink]="['/newsdetail']" [queryParams]="{aid:item.id}">{{key}}--{{item.name}}</a>
</li>
</ul>
<button type="button" (click)="gotoDetail($event)" tag='1'>新闻详情</button>
ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
public newsList: any[] = [{
id: '1',
name: '第一条新闻'
}, {
id: '2',
name: '第二条新闻'
}]
constructor(public router: Router) { }
ngOnInit(): void {
}
gotoDetail(ev) {
var target = ev.target,
id = target.getAttribute('tag');
this.router.navigate(['newsdetail'], {
queryParams: {
name: 'laney',
id: id
},
skipLocationChange: true //隐藏 url里的参数
//默认是false
})
}
}
子组件接收参数
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-newsdetail',
templateUrl: './newsdetail.component.html',
styleUrls: ['./newsdetail.component.less']
})
export class NewsdetailComponent implements OnInit {
constructor( public route:ActivatedRoute) { }
ngOnInit(): void {
//获取参数
// console.log(this.route.queryParams.value)
// this.route.queryParams.value //错误
this.route.queryParams.subscribe((data)=>{
console.log(data)
})
}
}
第二种
html
<!-- 路径传参 -->
<ul>
<li *ngFor="let item of productList; let key = index;">
<!-- 动态路由传参 ,下面2种方式都可以-->
<!-- /product/detail/1 -->
<!-- <a [routerLink]="['/product/detail/'+item.id]" >{{key}}--{{item.name}}</a> -->
<a [routerLink]="['/product/detail/',item.id]">{{key}}--{{item.name}}</a>
</li>
</ul>
<button type="button" (click)='gotoDetail($event)' tag='1'>跳转product到详情</button>
ts
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.less']
})
export class ProductComponent implements OnInit {
public productList:any[]=[{
id:'1',
name:'我是第一个产品'
},{
id:'2',
name:'我是第二个产品'
}]
constructor(public router:Router) { }
ngOnInit(): void {
}
gotoDetail(ev){
var target = ev.target,
id = target.getAttribute('tag');
this.router.navigate(['/product/detail/',id])
}
}
子组件接收
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-productdetail',
templateUrl: './productdetail.component.html',
styleUrls: ['./productdetail.component.less']
})
export class ProductdetailComponent implements OnInit {
constructor(public route: ActivatedRoute) { }
ngOnInit(): void {
console.log(this.route.params);
this.route.params.subscribe((res) => {
console.log(res);
})
}
}