Reputation: 2204
Below is the mark up
<mat-card class="example-card" *ngFor="let filteredScreen of
filteredScreens" let i = index >
<mat-card-header>
<div mat-card-avatar class="example-header-image" >
<img mat-card-image class="list-img" src="
{{filteredScreen?.img}}" >
</div>
<mat-card-content class="names" [innerHTML]="filteredScreen.name
| highlight: name" >{{
filteredScreen?.name }}
</mat-card-content>
</mat-card-header>
</mat-card>
How can i change the
<mat-card>
background color on mouse click(not mouse hover) to any color,and
<mat-card-content>
color to any color permanently in angular. I have done changing the background color on mouse hover but i want it on click.
Upvotes: 2
Views: 23079
Reputation: 24472
directive is a good solution for this kind of thing and can be configurable like color for example and can be reusable on other component mean outside this component and you don't need to add extra logic inside current component.
import { Directive, HostBinding, Input,HostListener} from '@angular/core';
import { DomSanitizer, SafeStyle } from "@angular/platform-browser";
@Directive({
selector: '[clickColor]'
})
export class ClickColorDirective {
private toggle: boolean = false;
@Input() color: string = 'red';
constructor(private doms: DomSanitizer) { }
@HostBinding('style') get myStyle(): SafeStyle {
let style : string = this.toggle ? `background: ${this.color}` : '';
return this.doms.bypassSecurityTrustStyle(style);
}
@HostListener('click') onClick() {
this.toggle = !this.toggle;
}
}
template
<div clickColor>
Hello World from Angular
</div>
<div clickColor color='blue'>
Angular World
</div>
<div clickColor [color]="'#000'">
Batman !!!
</div>
Upvotes: 3
Reputation: 426
<mat-card [ngClass]="{'background-mad': x}" (click)="x = true">
<mat-card-content [ngClass]="{'color-mad': y}" (click)="y = true">
in the ts file
public x: boolean = false;
public y: boolean = false;
And in the css file add for example:
.background-mad {
background-color: red
}
.color-mad {
color: green
}
EDIT
html:
<span [style.color]="color" (click)="changeColor()">aaaa</span>
ts:
private list: any = [
'red',' green', 'blue'
];
public color: 'black';
changeColor() {
this.color1 = this.list[Math.floor(Math.random() * this.list.length)];
}
Upvotes: 1
Reputation: 9687
use @HostListener
I have create a demo on Stackblitz
@HostListener('click') onMouseClick() {
this.highlight(this.highlightColor || 'red');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
Upvotes: 3