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必须检查一个实例才能使其工作的属性?
首先,修改您的路由定义以允许路径参数,如下所示:
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 的一个分支
| 归档时间: |
|
| 查看次数: |
8977 次 |
| 最近记录: |