根据 url 差异修改组件视图
modify component view based on url difference
基本上,我希望只有一个视图可以在我的 angular 应用程序上列出博客文章。因此,要获得所有、最近和类别明智的博客文章列表,我将只使用一个组件。
http://localhost:4200/blog/category/technology
http://localhost:4200/blog/recent
http://localhost:4200/blog/post/1
以上两个 url(第一个和第二个)将显示不同的列表,但在相同的组件上。
我的路由器是这样的:
const routes: Routes = [
{path: 'blog', component: BlogpostListComponent},
{path: 'blog/post/:id', component: BlogpostDetailComponent},
{path: 'blog/category/:name', component: BlogpostListComponent},
];
那么我怎样才能对 BlogpostListComponent
进行更改,因为到目前为止,所有、最近和类别都显示相同的内容,因为我不知道如何根据 urls 进行区分.如果我能弄清楚如何理解 URL 模式的差异,那么我可以利用 *ngIf
并在同一组件中的不同 URL 上显示不同的内容。
在您的组件中注入 Router
,然后使用它来获取当前 URL:
import { Router } from '@angular/router';
currentRoute: string;
category: boolean;
constructor(
private router: Router
) { }
ngOnInit() {
this.currentRoute = this.router.url;
if (this.currentRoute.includes('category') {
this.category = true;
} else {
this.category = false;
}
}
然后在您的模板中:
<div *ngIf="category">
This is category mode.
</div>
<div *ngIf="!category">
This is regular mode.
</div>
基本上,我希望只有一个视图可以在我的 angular 应用程序上列出博客文章。因此,要获得所有、最近和类别明智的博客文章列表,我将只使用一个组件。
http://localhost:4200/blog/category/technology
http://localhost:4200/blog/recent
http://localhost:4200/blog/post/1
以上两个 url(第一个和第二个)将显示不同的列表,但在相同的组件上。
我的路由器是这样的:
const routes: Routes = [
{path: 'blog', component: BlogpostListComponent},
{path: 'blog/post/:id', component: BlogpostDetailComponent},
{path: 'blog/category/:name', component: BlogpostListComponent},
];
那么我怎样才能对 BlogpostListComponent
进行更改,因为到目前为止,所有、最近和类别都显示相同的内容,因为我不知道如何根据 urls 进行区分.如果我能弄清楚如何理解 URL 模式的差异,那么我可以利用 *ngIf
并在同一组件中的不同 URL 上显示不同的内容。
在您的组件中注入 Router
,然后使用它来获取当前 URL:
import { Router } from '@angular/router';
currentRoute: string;
category: boolean;
constructor(
private router: Router
) { }
ngOnInit() {
this.currentRoute = this.router.url;
if (this.currentRoute.includes('category') {
this.category = true;
} else {
this.category = false;
}
}
然后在您的模板中:
<div *ngIf="category">
This is category mode.
</div>
<div *ngIf="!category">
This is regular mode.
</div>