我们可以使用ActivatedRoute服务中的查询参数来实现此目的。 先在app-routing.module.ts中定义路由:
{ path: 'products/:id', component: ProductDetailComponent }
然后在ProductDetailComponent中,我们可以注入ActivatedRoute并使用其params属性来获取路由参数。
import { ActivatedRoute } from '@angular/router';
@Component({ selector: 'app-product-detail', templateUrl: './product-detail.component.html', styleUrls: ['./product-detail.component.css'] }) export class ProductDetailComponent implements OnInit {
productId: number; products: any = [ { id: 1, name: 'Product 1', category: 'Category 1' }, { id: 2, name: 'Product 2', category: 'Category 2' }, { id: 3, name: 'Product 3', category: 'Category 1' }, { id: 4, name: 'Product 4', category: 'Category 2' } ];
constructor(private route: ActivatedRoute) { }
ngOnInit() { this.route.params.subscribe(params => { this.productId = +params['id']; }); } }
在template中,我们可以使用*ngIf指令来根据productId显示对应的products数组元素。
Product 1 Details
Product 2 Details
Product 3 Details
Product 4 Details
如果我们有很多元素需要显示,可以使用ngSwitch结构来替换多个*ngIf。