【问题标题】:Passing data via a routerLink angular router template expression?通过 routerLink 角度路由器模板表达式传递数据?
【发布时间】:2018-05-26 21:01:15
【问题描述】:

使用 stackblitz 起点,我添加了以下路由:

    const routes : Routes = [ {path: 'hello', 'component': HelloComponent}];


    @NgModule({
      imports:      [ 
        RouterModule.forRoot(routes, {enableTracing: true}) ],
      declarations: [ AppComponent, HelloComponent ],
    })

还在app-component.html模板中添加了<router-outlet>,点击以下链接时会呈现hello-component

<a routerLink="hello" routerLinkActive="active">hello</a>

但是点击链接时hello-component组件的属性为空:

@Input() name: string;

有没有办法通过模板表达式传入一个值,以便在组件上设置 name 属性,并在单击 hello 锚点的 hello-component.ts 的模板字符串中进行评估?

hello 组件如下所示,仅供参考:

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

    @Component({
      selector: 'hello',
      template: `<h1>Hello {{name}}!</h1>`,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent  {
      @Input() name: string;
    }

似乎必须检查 ActivatedRoute 实例的属性才能使其正常工作?

【问题讨论】:

  • 你想在哪里设置值?在路由数组中,还是要将 URL 中的值作为 URL 参数传递?目前我没有看到你在哪里传递任何价值
  • 通过动态表达式中的路由器链接 .... 所以而不是 routerLink="hello" ... routerLink="此处的动态表达式 ...."
  • 好的,你能把链接添加到你的 stackblitz 吗?谢谢

标签: javascript html angular angular-router


【解决方案1】:

首先,修改您的路由定义以允许路径参数,如下所示:

const routes : Routes = [ 
  {path: 'crisis-center', 'component': HelloComponent}, 
  {path: 'hello/:name', 'component': HelloComponent}, 
  {path: '**', 'component': HelloComponent}
];

这将允许您将name 参数传递给/hello 路由。

要在组件中访问它,您需要订阅参数更改,如下所示:

export class HelloComponent  {
  @Input() name: string;

  constructor(private route: ActivatedRoute) {

  }

  ngOnInit(){
    this.route.paramMap.subscribe( params =>
        this.name = params.get('name')
    )
  }
}

最后,您可以通过routerLink 传递一个值,如下所示:

<a [routerLink]="['hello', routeOneName]" routerLinkActive="active">hello</a>

其中routeOneName 是在AppComponent 中声明的变量。

如果你想看的话,我已经为你的 StackBlitz here 创建了一个分支

【讨论】:

  • 还要注意routerLink周围有[]。那是因为我们分配的是一个数组而不是像“hello”这样的字符串
  • @Ole [routerLink] 周围的括号告诉 Angular = 后面的位应该被视为代码,而不仅仅是字符串。 ['hello', routeOneName] 周围的括号是因为这是一个数组,其中第一个元素是路径,第二个元素是您要传递的值。如果我们排除 [routerLink] 周围的括号,这将不再被视为一个数组,而只是一个字符串
  • 出于某种原因,这不适合我。 esp 将一些值作为 json 传递。我正在尝试的代码是:[routerLink]="['/pages/somepage',{ somekey1:1234 , key2:12345}]"
猜你喜欢
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 2018-09-14
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多