Reputation: 370
How can I change the color of text using Angular (TypeScript). I have a button that when clicked it changes the background color of the Header and Main section. But I want that SAME button to also change the color of the text. When I click I want the background, for example, in red and the text in white.
I will add some more information to this question.
I did something in "data.service.ts" for the same button (that is in main section) to also change the background color in Main section:
import { BehaviorSubject } from 'rxjs';
export class DataService {
private mensagemFonte = new BehaviorSubject <string> ('default value')
actualMensagem = this.mensagemFonte.asObservable();
constructor() { }
alteraMensagem (mensagem: string) {
this.mensagemFonte.next(mensagem)
}
}
Then, in "header.component.ts":
import { DataService } from '../../data.service';
export class HeaderComponent implements OnInit {
DarkTheme: string;
constructor(private data: DataService) { }
ChangeColor(color: string) {
this.data.alteraMensagem(color);
}
ngOnInit(): void {
this.data.actualMensagem.subscribe(mensagem => this.DarkTheme = mensagem)
}
}
And in the "header.component.html" (in here, I think that the importante part of code to this question is where I have "[style.background]=DarkTheme" and where you have "ChangeColor" , so I have:
<header>
<nav class="navbar navbar-expand-lg navbar-light navbar-custom sticky-top" style="padding: 0;"
[style.background]=DarkTheme>
<div class="container" style="padding: 50;">
<a class="navbar-brand text-center" href="#top" id="nav-icon">
<img class="img-fluid" src="../../../assets/img/logo.svg" width="100" height="100" />
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav col-8">
<li class="nav-item-1">
<a class="nav-link" href="#main">AS MARAVILHAS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#footer">CONTACTOS</a>
</li>
</ul>
<ul class="navbar-nav col-4 sim">
<li class="nav-item">
<a class="nav-link" style="cursor: pointer;" (click)="ChangeColor ('red')">MODO ESCURO</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
Upvotes: 0
Views: 15471
Reputation: 21658
Have a flag that toggles a class on and off for a block. Have that class control all the sytles you want to toggle
<div [ngClass]="{ yourStyle: yourToggleFlag }">Content to style with yourClass<div>
<button (click)="yourToggleFlag = !yourToggleFlag">Click</button>
Upvotes: 1
Reputation: 4572
I hope this helps
<div *ngIf="button.clicked"
[style.background]=" button.clicked ? 'green' : 'transparent' "
[style.color]=" button.clicked ? 'white' : 'black' "
>Your text</div>
Upvotes: 2