ОБНОВЛЕНО ANSWERУгловое 2: Navbar изменение цвета значка на основе маршрута
смотрите ниже первоначального вопроса. Но благодаря @Smit за то, что он привел меня к решению.
Вот обновленный Plunker с раствором: Updated Plunker
Теперь может быть лучшим способом решить эту проблему, но это, как у меня есть на данный момент.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router'
@Component({
selector: 'my-app',
template: `
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<div>
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" routerLink="home">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="red">Red <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="blue">Blue <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link"><i [ngClass]="setClasses()" class="icon-emotsmile icons"></i></a>
</li>
</ul>
</div>
</nav>
<div class="container-fluid">
<h1>Please click on links in navbar.</h1>
<hr><hr>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent implements OnInit {
someProperty = true;
anotherProperty = true;
setClasses() {
let classes = {
redText: this.someProperty,
blueText: this.anotherProperty,
};
return classes;
}
constructor(private router: Router) {
router.events.subscribe(e => {
if(e instanceof NavigationEnd) {
if(this.router.url === '/' || this.router.url === '/home') {
this.someProperty=false;
this.anotherProperty=false;
console.log("I am home")
}
else if(this.router.url === '/red') {
this.someProperty=true;
this.anotherProperty=false;
console.log("I am red")
}
else if(this.router.url === '/blue') {
this.someProperty=false;
this.anotherProperty=true;
console.log("I am blue")
}
else {
console.log("wrong")
}
}
});
}
ngOnit() {}
}
В основном я использовал маршрутизатор/NavigationEnd, чтобы найти маршрутизатор URL и оттуда я ngClass добавлять/удалять классы.
отредактированные на 02/21/2017
Я пытаюсь изменить цвет значков NavBar, когда пользователь просматривает определенные страницы.
Например, если пользователь просматривает домашнюю страницу, значки должны быть серыми, но когда пользователь просматривает красную страницу, значки будут красными.
Я использую Angular 2 и Bootstrap 4. Вот базовая настройка.
app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<div>
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" routerLink="home">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="red">Red <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="blue">Blue <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link"><i class="icon-emotsmile icons"></i></a>
</li>
</ul>
</div>
</nav>
<div class="container-fluid">
<h1>Please click on links in navbar.</h1>
<hr><hr>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent implements OnInit {
constructor() {}
ngOnit() {}
}
АПП-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RedComponent } from './red.component';
import { BlueComponent } from './blue.component';
import { HomeComponent } from './home.component';
const routes: Routes = [
{ path: 'red', component: RedComponent },
{ path: 'blue', component: BlueComponent },
{ path: 'home', component: HomeComponent },
{ path: '**', redirectTo: '/'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
home.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-home',
template: `
<h2>HOME</h2>
<p>I want the navbar to be <b>grey</b> and the smile icon to be <b>grey</b>.</p>
`
})
export class HomeComponent {}
red.component.ts и blue.component.ts в основном такие же, как home.component.ts.
Я создал plunker: Plunker
Вам будет сложно найти точную документацию и ответы, если вы все еще используете полностью устаревшую альфа-версию версии.46. Он был выпущен в финальной версии довольно долгое время. –
Извините, я использовал более раннюю версию углового. Я фактически использую текущую версию ... позвольте мне исправить плункер и отредактировать мой пост. – JessySue
@JBNizet Я отредактировал плункер. – JessySue