在Angular Material中使用动态路由,可以通过在路由配置中添加参数,根据不同的参数值动态生成路由。以下是一个示例代码:
首先,定义一个路由配置文件:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'details/:id', component: DetailsComponent }
];
在上面的例子中,我们定义了两个路由。第一个是根路由,指向HomeComponent,第二个是details路由,指向DetailsComponent,且包含一个参数:id。
接下来,在DetailsComponent组件中,可以通过ActivatedRoute服务获取路由参数的值,如下所示:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.scss']
})
export class DetailsComponent implements OnInit {
id: number;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.id = params['id'];
});
}
}
在上述代码中,我们注入了ActivatedRoute服务,并在ngOnInit()方法中使用params属性订阅了路由参数。当路由参数改变时,我们可以获取到新的值,并将其赋值给类的id属性。
最后,在HTML模板中获取参数的值并使用。示例代码如下:
Details for ID: {{id}}
通过这种方式,在Angular Material中使用动态路由就变得简单明了了。