Angular路由:如何通过routerLink模板表达式传递数据至组件?
解答:Angular路由加载组件时传递@Input属性的问题
首先明确说:直接通过模板表达式给路由加载的组件传@Input值是行不通的。因为HelloComponent是由Angular Router动态创建并插入到<router-outlet>中的,不是你在模板里直接声明的<hello [name]="'xxx'">这种形式,所以常规的输入绑定语法在这里不生效。
不过有几种替代方案可以实现给路由加载的组件传递值,下面分情况说明:
方案1:使用路由参数(借助ActivatedRoute)
如果希望通过URL参数传递动态值,就需要用到ActivatedRoute。
步骤1:修改路由配置
在路由中定义参数占位符:
const routes: Routes = [ { path: 'hello/:name', component: HelloComponent } ];
步骤2:在HelloComponent中获取参数
通过ActivatedRoute订阅路由参数的变化:
import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'hello', template: `<h1>Hello {{name}}!</h1>`, styles: [`h1 { font-family: Lato; }`] }) export class HelloComponent implements OnInit { @Input() name: string; constructor(private route: ActivatedRoute) {} ngOnInit() { // 订阅路由参数,支持参数变化时更新值 this.route.paramMap.subscribe(params => { this.name = params.get('name'); }); } }
步骤3:修改跳转链接
现在链接需要带上对应参数:
<a routerLink="hello/World" routerLinkActive="active">hello</a>
方案2:使用路由静态数据(借助ActivatedRoute)
如果传递的是固定值,不需要从URL获取,可以用路由配置里的data字段:
步骤1:修改路由配置
const routes: Routes = [ { path: 'hello', component: HelloComponent, data: { name: 'Static World' } // 配置静态数据 } ];
步骤2:在HelloComponent中读取数据
import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'hello', template: `<h1>Hello {{name}}!</h1>`, styles: [`h1 { font-family: Lato; }`] }) export class HelloComponent implements OnInit { @Input() name: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.data.subscribe(data => { this.name = data['name']; }); } }
方案3:从父组件通过router-outlet的activate事件传递
如果值来自父组件(比如AppComponent),可以利用<router-outlet>的activate事件获取组件实例,直接设置属性:
步骤1:修改AppComponent的模板
<a routerLink="hello" routerLinkActive="active">hello</a> <router-outlet (activate)="onComponentActivate($event)"></router-outlet>
步骤2:在AppComponent中处理激活事件
import { Component } from '@angular/core'; import { HelloComponent } from './hello.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { onComponentActivate(component: any) { // 判断组件类型,避免类型错误 if (component instanceof HelloComponent) { component.name = 'From Parent Component'; } } }
总结一下:如果是和URL关联的动态值,推荐用ActivatedRoute获取路由参数或数据;如果是父组件传递的静态/动态值,可以用activate事件的方式。直接用模板表达式给路由加载的组件传@Input是做不到的哦。
内容的提问来源于stack exchange,提问作者Ole
相关产品推荐
相关产品推荐

