【问题标题】:Change component's content according to the url in Angular 11根据 Angular 11 中的 url 更改组件的内容
【发布时间】:2021-06-01 22:55:06
【问题描述】:

我有一个组件,我想根据其中一个类别显示数据。 类别 - [运动、汽车、时尚、政治]。

在我的 NewsCategoriesComponent 中,我需要在单击导航按钮时显示更改的数据。

点击导航按钮后如何更改组件数据?

这是我的路线

const routes: Routes = [
  {path: '', component: DashboardComponent},
  {path: 'category', component: NewsCategoriesComponent},
  {path: '**', component: DashboardComponent}
];

【问题讨论】:

  • 很可能通过Resolver 读取ActivatedRoute 并根据给定的category 加载数据。
  • 请添加在组件中显示项目的代码

标签: javascript angular routes angular2-routing


【解决方案1】:

您可以在路线中将类别作为参数传递:

const routes: Routes = [
  {path: '', component: DashboardComponent},
  {path: 'category/:category', component: NewsCategoriesComponent},
  {path: '**', component: DashboardComponent}
];

然后从 NewsCategoriesComponent 中的路由中读取参数:

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-news-categories',
  templateUrl: './news-categories.component.html',
  styleUrls: ['./news-categories.component.css']
})

export class NewsCategoriesComponent {
  category: string;

  constructor(private actRoute: ActivatedRoute) {
    this.category = this.actRoute.snapshot.params.category;
  }
}

【讨论】:

  • 点击导航按钮后它只显示正确的内容一次,它没有改变。
  • 我需要查看您的组件的代码才能查明问题。
猜你喜欢
  • 1970-01-01
  • 2019-11-01
  • 2017-08-19
  • 1970-01-01
  • 2013-05-07
  • 2013-05-29
  • 2021-10-17
  • 2012-10-27
  • 2019-03-25
相关资源
最近更新 更多