Changing background color with typescript

Discussão em 'Angular' iniciado por Adil, Janeiro 19, 2025.

  1. Adil

    Adil Guest

    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;
    }
    }

    Continue reading...

Compartilhe esta Página