N. *_*sev 6 router directive typescript angular
我想在我的Angular2应用程序中使用Semantic UI.问题是我找不到更改默认名称"router-link-active"类的路由器设置.我需要它被称为"活动"才能使菜单正确显示.
据我了解,这种设置不存在.我在Vue.JS中看过它,所以我希望它也在那里.请求开发人员解决这个问题是个好主意吗?
所以.我们需要编写一个自定义指令,将"active"类添加到具有"router-link-active"类的所有DOM元素,但我也遇到了一些问题.
有一个类似的问题,但答案太复杂,不适合我.所以我读了一些文档,决定做更好的事情:
commons.ts:
@Directive({
selector: '.router-link-active',
host: {'[class.active]': 'trueConst'} //just 'true' could also work I think...
})
export class ActiveRouterLinkClass {
trueConst: boolean = true; //...if 'true' works we don't need this
}
Run Code Online (Sandbox Code Playgroud)
然后我将ActiveRouterLinkClass导入到我的main.component.ts并将其添加到组件的指令列表中.不幸的是,现在我有这个错误:"EXCEPTION:组件'Main'视图上的意外指令值'undefined'".请解释我做错了什么!
Angular 不会将指令或组件应用于动态应用的选择器。如果类.router-link-active添加到链接是动态的,因此将不起作用。
您可以做的是使用更通用的选择器,例如[routerLink]和 ,而不是读取是否.router-link-active使用 an 设置@Input()并使用主机绑定设置所需的类。
@Directive({
selector: '[routerLink]')
export class RouterLinkReplaceClass {
// add class `my-active` when `myActiveClass` is `true`
@HostBinding('class.my-active')
// read `router-link-active` class state
@Input('class.router-link-active')
myActiveClass: bool = false;
}
Run Code Online (Sandbox Code Playgroud)
另请参阅在 Angular 2 中,如何将自定义类分配给活动路由器链接?
更新
因为添加/删除类myActiveClass时未更新,所以router-link-active我修改了指令以与指令相同的方式获取有关活动路由的信息RouterLink:
import {ROUTER_DIRECTIVES, RouteConfig, Router, Instruction} from 'angular2/router';
@Directive({
selector: '[routerLink]'
})
export class RouterLinkReplaceClass {
//@Input('class.router-link-active')
// myActiveClass: boolean = false;
private _navigationInstruction: Instruction;
@Input('routerLink')
private _routeParams: any[];
constructor(private _router: Router) {
// we need to update the link whenever a route changes to account for aux routes
this._router.subscribe((_) => this._updateLink());
}
private _updateLink(): void {
this._navigationInstruction = this._router.generate(this._routeParams);
}
@HostBinding('class.my-active')
get isRouteActive(): boolean {
return this._navigationInstruction ? this._router.isRouteActive(this._navigationInstruction) : null;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1420 次 |
| 最近记录: |