【问题标题】:how to do routing inside multiple instances of same component in angular 6如何在角度 6 中在同一组件的多个实例中进行路由
【发布时间】:2019-06-26 02:06:35
【问题描述】:

在我的 POC 中,我显示了两个仪表板实例。我希望孩子出现在组件的相应实例中。

但当前的行为是,即使我在第一个实例中单击按钮,子项也会在第二个实例本身中呈现。

仪表板组件.html

<div class="border">
  <p>
    dashboard works!
  </p>
  <button [routerLink]="['child1']">one</button>
  <button [routerLink]="['child2']">two</button>
  <div class="border m-1">
    <router-outlet></router-outlet>
  </div>
  <p>-----------------------------------------------</p>
</div>

app.component.html

<div class="row">

  <app-dashboard></app-dashboard>    // instance 1

  <app-dashboard></app-dashboard>   //  instance 2

</div>

app.routing.module.ts

const routes: Routes = [
  { path: 'child1',
  component: ChildOneComponent
  },
  {
    path: 'child2',
    component: ChildTwoComponent
  }
];

child-one.component.html

<p>
  child-one works!
</p>

child-two.component.html

<p>
  child-two works!
</p>

一旦组件加载,我想在子 1 和子 2 中编写额外的代码。

谁能告诉我哪里出错或采取哪种方法?我已经尝试过使用辅助路由并将 id 分配给路由。但他们没有工作。

我只想创建同一个组件的多个实例并在它们内部启用路由,以便路由的特定组件在各自的实例中呈现。

【问题讨论】:

    标签: angular routing angular6 angular-routing router-outlet


    【解决方案1】:

    Router 是一个全局组件,因此它不属于某个组件。

    如果你有很多实例,你需要使用一个函数来重新加载一个实例。

    喜欢:

    Dashboard component.html

        <div class="border">
          <p>
            dashboard works!
          </p>
          <button (click)='routeone()'>one</button>
          <button (click)='routetwo()'>two</button>
            <div class="border m-1">
              {{mydata}}
           </div>
          <p>-----------------------------------------------</p>
        </div>
    

    Dashboard component.ts

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    @Component({
      selector: 'app-dashboard',
      templateUrl: './dashboard.component.html',
      styleUrls: ['./dashboard.component.css']
    })
    export class DashboardComponent implements OnInit {
    
      mydata;
      constructor( private router: Router) { }
    
      ngOnInit() {
      }
    
      routeone(){
        this.mydata = 'childOne'
      }
      routetwo(){
        this.mydata = 'childTwo'
      }
    
    }
    

    【讨论】:

    • 实际上我需要 child1 和 child2 成为组件,以便我可以在其中编写额外的代码。
    • 在这种情况下,将您的子组件一和二包含在您的仪表板组件中,然后根据 url 更改显示的组件。如果你需要,我可以展示实现
    • 是的。你能告诉我一次实现吗?我没有得到我做错的地方。我必须使用路由而不是使用 ngSwitch。
    • 您不能使用路由并选择您重新加载的组件的女巫实例。在 Angular 中,您只能在页面上拥有一个路由器实例。为什么你还需要在同一页面上有两个仪表板?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2019-11-14
    • 2018-11-21
    • 2018-07-11
    • 2020-04-26
    • 2020-06-21
    相关资源
    最近更新 更多