Before switching on angular I worked in javascript
. I want to change value of css
properties of certain elements in typescript. But I found that you can not change it like in javascript
: name.style.color='red'
.
With javascript
I would write:
HTML:
<div id="blue" style="background-color:red;">
Hello
</div>
<button id="it">Press</button>
JS:
let blue=document.getElementById("blue");
let it=document.getElementById("it");
it.onclick= ()=> blue.style.backgroundColor="blue";
But in typescript it doesn't work: HTML:
<div id="blue" style="background-color:red;">
Hello
</div>
<button (click)="switch()">Press</button>
TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my_app_2';
blue=document.getElementById("blue");
switch() {
this.blue.style.backgroundColor="blue";
}
}
I found one soultion, but I would like to know is there any more 'natural' way to do it like in javascript. Here code of that solution: HTML:
<div id="blue" [ngStyle]="this.clicked==true?{'background-color':'blue'}:{'background-color':'red'}">
Hello
</div>
<button (click)="switch()">Press</button>
TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my_app_2';
clicked=false;
switch() {
this.clicked=!this.clicked;
}
}
CodePudding user response:
Use Renderer2
's function setStyle
.
In Angular, avoid using document
, instead you should use @ViewChild
.
Example:
<!-- your-component.html -->
<div #blue></div>
// your-component.ts
export class MyComponent {
@ViewChild('blue') blue: ElementRef;
// Inject Renderer2 in your constructor
constructor(private renderer: Renderer2) { }
// Use it in your function
switch () {
this.renderer.setStyle(this.blue.nativeElement, 'background-color', 'blue');
}
}
CodePudding user response:
You can use ngClass
while setting the value to a function or property
In controller:
import { Component } from '@angular/core';
@Component({
// ...
})
export class AppComponent {
clicked = false;
switch() {
this.clicked = !this.clicked;
}
getBackgroundColor(): string {
if (this.clicked) {
return 'blue';
}
return 'red';
}
}
In template:
<div id="blue" [ngStyle]="{'background-color': getBackgroundColor()}">
Hello
</div>
<button (click)="switch()">Press</button>