Reputation: 467
I want to change style of my class based on screen size, like this
<p [ngStyle]="{'color': isMobile() ? 'red' : 'blue'}">Lorem Ipsum</p>
This piece of code is calling method in my component.ts
isMobile() {
return window.innerWidth < 640;
}
But from what I see, this function is called only once I click somewhere on the window, not while resizing. How can I make that happen instantly?
Upvotes: 0
Views: 44
Reputation: 69
You can use media queries like below(Sass):
.color-size {
color: blue;
@media screen and (max-width: 640px) {
color: red;
}
}
or pure css:
.color-size {
color: blue;
}
@media screen and (max-width: 640px) {
.color-size {
color: red;
}
}
If you want to do it by events in ts:
isMobile: boolean;
@HostListener('window:resize', ['$event'])
onResize(event) {
if (event.target.innerWidth < 640) {
this.isMobile = true;
} else {
this.isMobile = false;
}
}
and template will be:
<p (window:resize)="onResize($event)" [ngStyle]="{ color: isMobile ? 'red' : 'blue' }">Lorem Ipsum</p>
Upvotes: 1