通过 routerLink 角度路由器模板表达式传递数据?

Ole*_*Ole 3 html javascript angular angular-router

玩弄 stackblitz 的起点,我添加了以下路由:

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


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

还向模板添加了 a <router-outlet>,单击以下链接时会呈现 :app-component.htmlhello-component

<a routerLink="hello" routerLinkActive="active">hello</a>
Run Code Online (Sandbox Code Playgroud)

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

@Input() name: string;
Run Code Online (Sandbox Code Playgroud)

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

仅供参考,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;
    }
Run Code Online (Sandbox Code Playgroud)

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

use*_*994 9

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

const routes : Routes = [ 
  {path: 'crisis-center', 'component': HelloComponent}, 
  {path: 'hello/:name', 'component': HelloComponent}, 
  {path: '**', 'component': HelloComponent}
];
Run Code Online (Sandbox Code Playgroud)

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

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

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

  constructor(private route: ActivatedRoute) {

  }

  ngOnInit(){
    this.route.paramMap.subscribe( params =>
        this.name = params.get('name')
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

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

<a [routerLink]="['hello', routeOneName]" routerLinkActive="active">hello</a>
Run Code Online (Sandbox Code Playgroud)

routeOneName声明的变量在哪里AppComponent

如果你想看的话,我在这里创建了你的 StackBlitz 的一个分支

  • @Ole `[routerLink]` 周围的括号告诉 Angular,`=` 之后的位应该被视为代码,而不仅仅是字符串。`['hello', routeOneName]` 两边的括号是因为它是一个数组,其中第一个元素是路径,第二个元素是您要传递的值。如果我们排除了 `[routerLink]` 周围的括号,这将不再被视为一个数组,而只是一个字符串 (4认同)