gpt4 book ai didi

javascript - 通过 routerLink Angular 路由器模板表达式传递数据?

转载 作者:行者123 更新时间:2023-11-29 17:44:45 25 4
gpt4 key购买 nike

研究一下 stackblitz 起点,我添加了以下路由:

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


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

还添加了一个<router-outlet>app-component.html模板,以及 hello-component单击以下链接时呈现:

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

然而hello-component上的属性单击链接时组件为空:

@Input() name: string;

有没有办法通过模板表达式传递一个值,以便在组件上设置 name 属性并在 hello-component.ts 中求值?的模板字符串与 hello anchor 被点击?

仅供引用,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必须检查实例的属性才能使其正常工作?

最佳答案

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

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如果你想看

关于javascript - 通过 routerLink Angular 路由器模板表达式传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50546969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com