【问题标题】:call angular components according to the URL根据 URL 调用角度组件
【发布时间】:2023-02-20 23:07:02
【问题描述】:

我正在建立一个网站,无论我使用什么网址,内容始终相同,只有一个组件发生变化。为此,我尝试使用应用程序路由和 ActivatedRoute 来做到这一点,问题是我不知道如何将条件添加到组件中。这是我的代码:

应用程序路由.modules.ts:

const routes: Routes = [
  {
    path: "",
    component: HomepageComponent,
    pathMatch: "full",
  },
  { path: ":property", component: HomepageComponent },
];

主页.component.html

<app-header-slider></app-header-slider>
<app-content></app-content>

<app-test></app-test>
<app-test-one></app-test-one>
<app-test-two></app-test-two>

<app-blog></app-blog>
<app-accordion></app-accordion>

主页.component.ts

constructor(public route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.paramMap.subscribe((params) => {
      this.name = params.get("property");
      console.log(this.name);
    });
  }

console.log(this.name) 我对 this.name 做的是正确的,但现在我需要实现它

<app-test></app-test>
<app-test-one></app-test-one>
<app-test-two></app-test-two>

一个 if 语句,例如,如果 url 是 /test-one,请显示 app-test-one,如果是 /test-two,请显示 app-test-two,如果 url 为空 ('/')展示 。

但我不知道后者该怎么做。 非常感谢

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这是我的解决方案:

    <ng-container *ngIf="name==='test-one'">
      <app-test-one></app-test-one>
    </ng-container>
    

    【讨论】:

      【解决方案2】:

      如果我没理解错的话,你可以使用ngSwitch根据你的name属性显示不同的组件

      <ng-container [ngSwitch]="name">
        <app-test *ngSwitchCase="'name1'"></app-test>
        <app-test-one *ngSwitchCase="'name2'"></app-test-one>
        <app-test-two *ngSwitchCase="'name3'"></app-test-two>
        <app-fallback *ngSwitchDefault></app-fallback>
      </ng-container>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-06
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        • 2019-07-22
        • 2018-05-22
        相关资源
        最近更新 更多