基于URL动态更改DIV的css-角度

时间:2018-10-20 15:19:17

标签: javascript html css angular frontend

我有一个问题,我想根据我所在的RouterModule更改第一个DIV(背景,宽度,高度...)的CSS,并且此DIV位于主app.component.html中

<div class="bg">
<div class="container-fluid">
<div class="row">
<div class="col-xl-2 col-lg-1 col-md-1 col-sm-1" id="logo">
  <a routerLink=""><b>Logo</b></a>
</div>
<div id="navigation" class="col-xl-8 col-lg-10 col-md-10 col-sm-10">
  <ul>
    <li><a routerLink="/zivljenjepis">O MENI</a></li>
    <li><a routerLink="/jeziki">JEZIKI</a></li>
    <li><a routerLink="/projekti">PROJEKTI</a></li>
    <li><a routerLink="/kontakt">KONTAKT</a></li>
  </ul>
</div>
</div>
</div>
</div>
<router-outlet></router-outlet>

您有什么建议吗? 谢谢

2 个答案:

答案 0 :(得分:1)

[routerLinkActive]使您可以在链接的路由变为活动状态时向元素添加CSS类。

HTML:

<a routerLink="/user/bob" routerLinkActive="class1">Bob</a>

CSS:

.class1 { background-color: red }

https://angular.io/api/router/RouterLinkActive

答案 1 :(得分:1)

您可以做的是在router.events上订阅,以了解何时发生导航。然后在NavigationEnd上检索当前路径路径值,并使用ngClass将其作为CSS类应用于所需的HTML元素。

例如,这意味着导航到home页面将在您应用home的元素上添加ngClass类。然后,您可以设置CSS类以根据需要设置元素的样式。

此处提供StackBlitz示例:https://stackblitz.com/edit/angular-stackoverflow-52907143

app.component.html

<div class="bg" [ngClass]="bgClass">
  <div id="logo">
    <a routerLink=""><b>Logo</b></a>
  </div>
  <div id="navigation">
    <ul>
      <li><a routerLink="/home">Home</a></li>
      <li><a routerLink="/products">Products</a></li>
      <li><a routerLink="/about">About</a></li>
    </ul>
  </div>
</div>
<router-outlet></router-outlet>

app.component.ts

import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  bgClass = 'default';

  constructor(
    private router: Router,
  ) {
    // subscribe to router navigation
    this.router.events.subscribe(event => {
      // filter `NavigationEnd` events
      if (event instanceof NavigationEnd) {
        // get current route without leading slash `/`
        const eventUrl = /(?<=\/).+/.exec(event.urlAfterRedirects);
        const currentRoute = (eventUrl || []).join('');
        // set bgClass property with the value of the current route
        this.bgClass = currentRoute;
      }
    });
  }
}

app.component.css

.default {
  background: lightgray;
}

.about {
  background: lightpink;
}

.home {
  background: powderblue;
}

.products {
  background: lightgreen;
}