2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Angular】動的にCSSを変更する方法

Last updated at Posted at 2022-08-01

はじめに

CSSを動的に変更する方法でバインディングや直接DOM操作と何パターンかあるのでまとめることにしました。
今後、Angularで実装する方の参考になればと思います。

バージョン

・Angular: 9.1.11
バージョンの確認方法については過去記事に記載しております。

NgStyle

参考:Angular:NgStyle

test.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html'
})
export class TestComponent {
  color = "red";
  style = {'width': '50px', 'height': '50px','background-color':'red'};

  constructor() { }

  onClickChangeColor() {
    this.color = "blue";
  }

  onClickChangeObject() {
    this.style = {'width': '100px', 'height': '100px','background-color':'blue'};
  }
}
test.component.html
<div [ngStyle]="{'width': '100px', 'height': '100px','background-color': color}"></div>
<button (click)="onClickChangeColor()">カラー変更</button>

<div [ngStyle]="style"></div>
<button (click)="onClickChangeObject()">オブジェクト変更</button>

style binding

参考:Angular:Class and style binding

test.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html'
})
export class TestComponent {
  color1 = "red";
  color2 = "red";
  style = {'width': '50px', 'height': '50px','background-color':'red'};

  constructor() { }

  onClickChangeColor1() {
    this.color1= "blue";
  }

  onClickChangeColor2() {
    this.color2= "blue";
  }

  onClickChangeObject() {
    this.style = {'width': '100px', 'height': '100px','background-color':'blue'};
  }
}
test.component.html
<div [style.background-color]="color1" style="width: 100px; height : 100px;"></div>
<button (click)="onClickChangeColor1()">カラー変更1</button>

<div [style]="{'width': '100px', 'height': '100px','background-color': color2}"></div>
<button (click)="onClickChangeColor2()">カラー変更2</button>

<div [style]="style"></div>
<button (click)="onClickChangeObject()">オブジェクト変更</button>

Renderer2

参考:Angular:Renderer2

test.component.ts
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html'
})
export class TestComponent {
	@ViewChild('element') public element: ElementRef;

  constructor(
    private renderer: Renderer2
  ) { }

  ngAfterViewInit(): void {
    console.log(this.element);
  }

  onClickChangeColor() {
    this.renderer.setStyle(this.element.nativeElement, 'background-color', 'blue');
  }
}
test.component.html
<div #element style="width: 100px; height: 100px; background-color: red"></div>
<button (click)="onClickChangeColor()">カラー変更</button>

注意

下記二つは推奨されていません。
基本的にはDOMに直接アクセスするのは良くないみたいです。
詳しくはAngular:ElementRef#propertiesUSE WITH CAUTIONをご確認ください

ViewChild

参考:Angular:ViewChild

test.component.ts
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html'
})
export class TestComponent {
	@ViewChild('element') public element: ElementRef;

  constructor() { }

  public ngAfterViewInit(): void {
    this.element.nativeElement.style.width = "100px";
    this.element.nativeElement.style.height = "100px";
    this.element.nativeElement.style.backgroundColor = "red";
  }

  onClickChangeColor() {
    this.element.nativeElement.style.backgroundColor = "blue";
  }
}
test.component.html
<div #element></div>
<button (click)="onClickChangeColor()">カラー変更</button>

ViewChildren

参考:Angular:ViewChildren
#elementsにはQueryListがセットされているため詳細な使い方はAngular:QueryListを確認してください。

test.component.ts
import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html'
})
export class TestComponent {
	@ViewChildren('elements') public elements: QueryList<ElementRef>;

  constructor() { }

  public ngAfterViewInit(): void {
    console.log(this.elements);
  }

  onClickChangeColor() {
    for(let element of this.elements) {
      element.nativeElement.style.width = "100px";
      element.nativeElement.style.height = "100px";
      switch(element.nativeElement.id) {
        case "ele1":
          element.nativeElement.style.backgroundColor = "red";
          break;

        case "ele2":
          element.nativeElement.style.backgroundColor = "blue";
          break;

        case "ele3":
          element.nativeElement.style.backgroundColor = "yellow";
          break;
      }
    }
  }
}
test.component.html
<div #elements id="ele1"></div>
<div #elements id="ele2"></div>
<div #elements id="ele3"></div>
<button (click)="onClickChangeColor()">カラー変更</button>

補足

  • #element,#elementsはテンプレート変数です。テンプレート変数はAngular:Understanding template variablesを確認してください。
  • ViewChild、ViewChildrenで#element,#elements取得時の注意
    • #element,#elementsはngAfterViewInit()以降で取得することができます。
    • ちなみにngAfterViewInit()はライフサイクルの一つです。
    • ライフサイクルの順序は下記のようになっています。
      • ngOnChanges()
      • ngOnInit()
      • ngDoCheck()
      • ngAfterContentInit()
      • ngAfterContentChecked()
      • ngAfterViewInit()
      • ngAfterViewChecked()
      • ngOnDestroy()

参考文献

Angular:NgStyle
Angular:Class and style binding
Angular:Renderer2
Angular:ViewChild
Angular:ViewChildren
Angular:ElementRef#properties
Angular:QueryList
Angular:Understanding template variables

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?