【问题标题】:Pass parameter to component将参数传递给组件
【发布时间】:2018-09-21 03:14:21
【问题描述】:

我有以下 Angular 6 组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-site-layout',
  templateUrl: './site-layout.component.html'
})

export class SiteLayoutComponent implements OnInit {

  @Input() version: string;

}

我有以下路线定义:

const appRoutes: Routes = [

  { 
    path: '', 
    component: SiteLayoutComponent,
    children: [
      { path: 'about', component: AboutComponent },
      { path: 'team', component: TeamComponent }
    ]
  }

  // Other routes

]

是否可以在中传递版本值:

{ path: 'about', component: AboutComponent }

我将SiteLayoutComponent 用作其他页面的“母版页”。

SiteLayoutComponent 根据版本值略有不同。

例如,AboutComponent 可能需要使用版本 1 的 SiteLayoutComponentTeamComponent 可能使用版本 2 的 SiteLayoutComponentTeamComponent

这有意义吗?

更新

我创建并在线示例:

http://stackblitz.com/edit/angular-rxxfff

当点击“团队”时,它应该会出现“布局组件 1.0”,但会出现“布局组件”。

我错过了什么?

【问题讨论】:

  • 我已经发布了一个答案,我不确定这就是你要找的
  • 我看不到你的答案。你删了吗?
  • 能不能刷新一下,我已经删了重新发了

标签: angular angular5 angular6


【解决方案1】:

您可以像这样将版本保留为子路由上的数据

{ 
    path: '', 
    component: SiteLayoutComponent,
    children: [
      { path: 'about', component: AboutComponent,data: { version: "1.0" } },
      { path: 'team', component: TeamComponent,data: { version: "2.0" } }
    ]
  }

您可以使用父组件(SiteLayoutComponent)中的 ActivateRoute 来访问它,并根据版本进行更改

constructor(
    private route: ActivatedRoute,

  ) {}


var version= this.route.snapshot.firstChild.data["version"]

有用的链接

How can I access an activated child route's data from the parent route's component?

【讨论】:

  • 我根据您的建议创建了一个在线示例:stackblitz.com/edit/angular-rxxfff ... 当您单击“团队”时,它应该出现“布局组件 1.0”,但只显示“布局组件”。我错过了什么?
  • @MiguelMoura 这是因为您将版本返回到变量中,所以角度假设它是私有的并且无法访问 html。而是创建一个属性。查看更新堆栈闪电战stackblitz.com/edit/angular-a3kfnb?file=src/app/…
  • @MiguelMoura 你检查了更新的堆栈闪电战吗??
  • 是的,我查过了。谢谢
【解决方案2】:

关注这个

{ path: 'about/:version', component: AboutComponent }

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

export class SiteLayoutComponent implements OnInit {

version: string;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.params.subscribe(params => {
    if (params.hasOwnProperty('pid') && params['pid'] != ''{
     this.version = params['version']; 
    }

  });
}

【讨论】:

  • 我不希望参数在 about 路由中。我的意思是,我需要设置 AboutComponentLayout 使用哪个版本的 SiteComponentLayout。而且它永远都是一样的。
  • 我添加了一个带有在线示例的更新。它几乎可以工作了。只有参数值不显示。我错过了什么?
猜你喜欢
  • 2021-01-18
  • 1970-01-01
  • 2020-02-06
  • 2018-02-04
  • 1970-01-01
  • 2017-10-24
  • 2018-08-03
  • 2011-06-16
  • 2021-04-03
相关资源
最近更新 更多