ryy77
ryy77

Reputation: 1294

How to set style for an element in typescript?(Angular)

How can I set the background colour for an item within an if statement in typescript? I used querySelector but the answer can use anything to achieve the result.

The selector is (.mat-step:nth-child(2) .mat-step-header .mat-step-icon-selected).

Here is the code in a stackblitz.

I would appreciate any help!

Upvotes: 1

Views: 3346

Answers (1)

dev-dan
dev-dan

Reputation: 6283

The stackblitz example can be helpful but there is a lot in there to summarise what you are askign for, this answer is a generic way of doing so, meaning you can apply it to your code as and where you see fit.

Declare you boolean.

public value = true;

Now declare the CSS class you would like to use.

.exmaple-class {
    background: red;
}

Then on the selected HTML element you want to apply the class.

<div [class.example-class]="value === true"></div>

or just

<div [class.example-class]="value"></div>

As this still equates to true. If value were set to false then the class would not be applied.

If you want to start building more classes and options for a specific element you can look into Angular's ngStyle.

Add in this, think this is what you are also asking for, little different. It only runs after the view is loaded, not working in you example because the HTML has not yet been drawn.

  public ngAfterViewInit(): void
  {
      this.changeColour();
  }

  public changeColour() {
      document.querySelector<HTMLInputElement>(".mat-step-icon-selected").style.backgroundColor = 'red';
  }
}

Then add a click event to ensure that each time you select something the selector is updated.

<div class="center-contrainer" (click)=changeColour()>

Upvotes: 4

Related Questions