简体   繁体   English

基于路由的CSS样式-Angular2

[英]CSS style base on route - Angular2

On the home page I want my logo to be 3x as big. 在主页上,我希望徽标大3倍。 Then when you select a menu option and the router opens a different page it should shrink down to normal size again. 然后,当您选择菜单选项并且路由器打开另一个页面时,它应该再次缩小到正常大小。

I was trying to do it by setting a variable to the page name and having the CSS change based on that. 我试图通过将变量设置为页面名称并基于此更改CSS来做到这一点。

<li [class.homeLogo]="home === 'Home'">

The problem is if someone types the route into the browser URL instead of clicking on the menu button it throws the whole thing off. 问题是,如果有人在浏览器URL中输入路由,而不是单击菜单按钮,则会使整个过程丢掉。 It also resets if the page is refreshed. 如果刷新页面,它也会重置。

Is there a way to access what route is currently being displayed so that I can ensure the CSS is tied to the page and not a variable? 有没有一种方法可以访问当前显示的路由,从而确保CSS绑定到页面而不是变量?

The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. $ location服务解析浏览器地址栏中的URL(基于window.location),并使该URL可用于您的应用程序。 Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar. 地址栏中URL的更改会反映到$ location服务中,而$ location所做的更改会反映到浏览器地址栏中。

The $location service: $ location服务:

Exposes the current URL in the browser address bar, so you can 在浏览器地址栏中显示当前URL,因此您可以

  • Watch and observe the URL. 观察并观察URL。

  • Change the URL. 更改URL。

Synchronizes the URL with the browser when the user 当用户将URL与浏览器同步时

  • Changes the address bar. 更改地址栏。

  • Clicks the back or forward button (or clicks a History link). 单击后退或前进按钮(或单击“历史记录”链接)。

  • Clicks on a link. 点击链接。

Represents the URL object as a set of methods (protocol, host, port, path, search, hash). 将URL对象表示为一组方法(协议,主机,端口,路径,搜索,哈希)。

For more information see Developer Guide: Using $location 有关更多信息,请参见开发人员指南: 使用$ location。

I would set the class at a higher point—say, the <body> . 我可以将类设置得更高一些,例如<body>

<body class="{{controllerName}}">

Then you can control your logo size. 然后,您可以控制徽标大小。

.logo {
  // regular old logo size
}

.home .logo {
  // 3x, baby!
}
@Component({
  selector: 'my-app',
  template: `...`
})
export class AppComponent {
  @HostBinding('class.homeLogo') isHome:boolean = false;

  constructor() {
    router.changes.subscribe(() => {
      this.isHome = getCurrentRoute() == '/home';
    });
  }
}

then you can use global style like 那么你可以使用像

<style>
  .logo {
    .... /* make it small */
  }
  .homeLogo > .logo {
    .... /* make it big */
  }
</style>

or a local style 或当地风格

@Component({
  selector: 'my-app',
  styles: [`
    :host .logo {
      .... /* make it small */
    }
    :host(.homeLogo) {
      .... /* make it big */
    }`
  ],
  template: `...`
})

You can give a try to this @Directive I have wrote. 您可以尝试@Directive我写的这个@Directive You should only change it to fit you needs. 您只应更改它以适合您的需求。

    import {Directive, ElementRef, Renderer, Input, OnInit} from '@angular/core'; 
import {Router, NavigationEnd} from '@angular/router';

@Directive({
    selector:  '[if-routes]'

})
export class IfRoutesDirective implements OnInit { 

    @Input("if-routes") routes : string[] = [];
    @Input("unless-routes") unlessRoutes : string[] = [];
    @Input("apply-styles") applyStyles : Object; 

    constructor(private _router : Router, 
                private _elemRef : ElementRef, 
                private _renderer: Renderer) {    
    }

    ngOnInit() { 
         //console.log(this.routes); 
         //console.log(this.unlessRoutes);

         this._router.events.subscribe(evt => {
           if(evt instanceof NavigationEnd) { 
                var url = evt.urlAfterRedirects;
                //console.log(url);
                if(this.routes.indexOf(url) >= 0 || this.routes.indexOf('**') >= 0) { 
                    // add element to DOM
                    // console.log("if routes matched!"); 
                    this._renderer.setElementStyle(this._elemRef.nativeElement, "display", "block"); 
                }  
                if(this.unlessRoutes.indexOf(url) >= 0 || this.unlessRoutes.indexOf('**') >= 0) { 
                    // remove element from DOM
                    // console.log("unless routes matched!");
                    this._renderer.setElementStyle(this._elemRef.nativeElement, "display", "none"); 
                } 

                if(this.applyStyles != null && ( this.routes.indexOf(url) >= 0 || this.routes.indexOf('**') >= ) ) { 

                    if(this.unlessRoutes.indexOf(url) <0) { 
                        // apply given styles to current DOM element 
                        for(var style in this.applyStyles) { 
                             this._renderer.setElementStyle(this._elemRef.nativeElement, style, this.applyStyles[style]); 
                        };
                    }
                } 
           }
        });
    }

}

Example usage: 用法示例:

<header-bar [if-routes]="['/some-route']" 
            [apply-styles]="{'position': 'fixed', 'margin-top' : '0px', 'margin-left' : '0px'}">
Loading header...
</header-bar>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM