Angular 与routerLink@Input()共享的组件
我想创建一个共享组件,它有一个按钮,当单击时,将用户路由到某个地方。路由应来自组件的使用者。我怎样才能做到这一点Angular 与routerLink@Input()共享的组件,angular,angular-routing,angular-components,Angular,Angular Routing,Angular Components,我想创建一个共享组件,它有一个按钮,当单击时,将用户路由到某个地方。路由应来自组件的使用者。我怎样才能做到这一点 我想我想让路由成为一个@Input()参数。这是一个好方法吗 共享组件 @Component({ selector: 'some-component', templateUrl: '<button [how do I bind the router parameters?]>Go Somewhere</button>' }) @Component(
我想我想让路由成为一个
@Input()
参数。这是一个好方法吗
共享组件
@Component({
selector: 'some-component',
templateUrl: '<button [how do I bind the router parameters?]>Go Somewhere</button>'
})
@Component({
selector: 'some-component',
template: `<button [routerLink]="componentLink"
[routerLinkActive]="['is-active']"
[routerLinkActiveOptions]="{ exact: true }">Go Somewhere</button>`
})
export class SomeComponent{
@Input()
componentLink: any[];
//Initialize it as an empty array for default values
@Input()
componentLinkActive: string[] = [];
//Same goes here
@Input()
componentLinkActiveOptions: {exact: boolean} = { exact: false }
}
@组件({
选择器:“某些组件”,
templateUrl:“去某个地方”
})
在其他模块中
<some-component [routerLink]="['blah', someDynamicValue]">
</some-component>
<some-component
[routerLink]="['blah-2', someDynamicValue2]"
[routerLinkActive]="['is-active']"
[routerLinkActiveOptions]="{ exact: true }">
</some-component>
<some-component
[componentLink]="['blah', someDynamicValue]"
[componentLinkActive]="['is-active']"
[componentLinkActiveOptions]="{ exact: true }"></some-component>
当然,以前有人问过这个问题?我似乎找不到它了……是的
@Input()
是一个很好的方法
试试这个
共享组件
@Component({
selector: 'some-component',
templateUrl: '<button [how do I bind the router parameters?]>Go Somewhere</button>'
})
@Component({
selector: 'some-component',
template: `<button [routerLink]="componentLink"
[routerLinkActive]="['is-active']"
[routerLinkActiveOptions]="{ exact: true }">Go Somewhere</button>`
})
export class SomeComponent{
@Input()
componentLink: any[];
//Initialize it as an empty array for default values
@Input()
componentLinkActive: string[] = [];
//Same goes here
@Input()
componentLinkActiveOptions: {exact: boolean} = { exact: false }
}
@组件({
选择器:“某些组件”,
模板:`到某处去`
})
导出类组件{
@输入()
componentLink:任何[];
//将其初始化为默认值的空数组
@输入()
componentLinkActive:字符串[]=[];
//这里也一样
@输入()
componentLinkActiveOptions:{exact:boolean}={exact:false}
}
在其他模块中
<some-component [routerLink]="['blah', someDynamicValue]">
</some-component>
<some-component
[routerLink]="['blah-2', someDynamicValue2]"
[routerLinkActive]="['is-active']"
[routerLinkActiveOptions]="{ exact: true }">
</some-component>
<some-component
[componentLink]="['blah', someDynamicValue]"
[componentLinkActive]="['is-active']"
[componentLinkActiveOptions]="{ exact: true }"></some-component>
另外,在您的共享组件模块中,请确保导入
路由模块
,谢谢John!我已经针对SomeComponent
的不同用法更新了我的问题。如何将routerLinkActive
和routerLinkActiveOptions
添加为可选输入参数?@spottedmahn刚刚更新了我的答案,我希望它能帮助您此解决方案的关键部分是确保
中的componentLink
用方括号括起来。否则Angular的参数解析逻辑将不会运行,参数值将是普通字符串(而不是数组)。