kittencup / angular2-ama-cn

angular2 随便问
691 stars 101 forks source link

如何在配置路由里面点击变色 #109

Open anghuang opened 8 years ago

anghuang commented 8 years ago

<a [routerLink]="['MobileList']">Mobile List <a [routerLink]="['CeoList']">CEO List

点击第一个背景改变,点第二个第一个背景还原第二个背景改变,

kittencup commented 8 years ago

差不多的可以看 https://github.com/kittencup/angular2-ama-cn/issues/36

这个应该有很多的实习方式。

anghuang commented 8 years ago

就是两个a标签里面的背景颜色,和别的没关系

kittencup commented 8 years ago

实现方式很多,随便写了个指令的实现方式

import {Component,Directive,ElementRef,Renderer} from 'angular2/core';
import {ROUTER_DIRECTIVES,RouteConfig,RouterLink,Router} from 'angular2/router';

@Component({
    selector: 'Index',
    template: `
        <h1>Index</h1>
    `
})
export class Index {

}

@Component({
    selector: 'Login',
    template: `
        <h1>Login</h1>
    `
})
export class Login {

}

@Directive({
    selector: '[bgColor]',
    inputs: ['bgColor']
})
class BgColor {

    bgColor:string;

    constructor(router:Router, routerLink:RouterLink, elementRef:ElementRef, renderer:Renderer) {
        router.subscribe((_:any) => {
            if (routerLink.isRouteActive) {
                renderer.setElementStyle(elementRef.nativeElement, 'background-color', this.bgColor);
            } else {
                renderer.setElementStyle(elementRef.nativeElement, 'background-color', '');

            }
        });
    }
}

@Component({
    selector: 'App',
    directives: [ROUTER_DIRECTIVES, BgColor],
    template: `
        <h1>App</h1>
         <ul>
             <li>
                <a [routerLink]="['/Index']" [bgColor]="indexBgColor">Index</a>
             </li>
             <li>
                <a [routerLink]="['/Login']" [bgColor]="loginBgColor">Login</a>
             </li>
        </ul>
        <router-outlet></router-outlet>
    `
})
@RouteConfig([
    {path: '/', component: Index, name: 'Index', useAsDefault: true},
    {path: '/login', component: Login, name: 'Login'}
])
export class App {

    indexBgColor:string = 'red';
    loginBgColor:string = 'blue';

}
guyoung commented 8 years ago

styles: [".router-link-active { background-color: red; }"],

完整代码:https://github.com/guyoung/GyPractice-Angular2Advanced/tree/master/apps/router_link_active