LoginSignup
7
5

More than 5 years have passed since last update.

Angularで、Component自体のCSSプロパティをTypeScriptから動的に変更する

Last updated at Posted at 2019-02-24

概要

AngularでComponentのサイズをウィンドウに合わせようとしたところ、公式のComponent Styleには「:hostセレクタでComponent自体のCSSを指定できるよ!」的なことしか書いてなかったのでTypeScriptから動的に自身のCSSを変化させる手順が不明だった。
ググって出てきたソースも動いたり動かなかったり割と曖昧なので、最終的に動いた方法を備忘としてここに書く。

手順

HostBindingデコレータをつけた変数をCompoentのメンバとして宣言して、変更したいCSSプロパティの頭にstyle.をつけてHostBindingデコレータの引数に渡す。
あとはその宣言したメンバに値を格納すると、CSSプロパティが格納した値に書き換わる。
heightしかやってないので型は何を選べばいいのか迷うけども、number型だと動かなくてstring型にして末尾にpxをつけたら動いたのでstring型が無難。

example.component.ts
import { Component, OnInit, HostBinding } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
  @HostBinding('style.height') height:string;//ここでstyle.<好きなプロパティ名>を指定するのが一番大事
  constructor() {
    let pxnum:number = window.innerHeight/2; //ここは入れたい数値を入れる。今回はウィンドウの高さの半分にした。
    this.height = (pxnum).toString() + "px";//指定したプロパティに対応した変数を書き換えると、その場で新しいCSSが適用される。
  }
  ngOnInit() {
  }
}

投稿用に試してる途中で気づいたけどもblockタグ扱いにしないと動かないのでそれを明記

example.component.css
p {
  background-color:#0000ff;/*pタグと背景の差をわかりやすくする用*/
}
:host {
  display:block;/*display:blockにしないとブロックタグとして使えるプロパティが適用されないので指定。position:fixedでも可。*/
  background-color:#7f7f7f;/*描画をわかりやすくする用*/
}

あとは、ng generate componentコマンドを使った時のまんま。

バージョン情報

確認に使ったブラウザはFirefox65.0、npmのバージョンは3.5.2

package.json
{
  "name": "test2",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.28.3",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.3.0",
    "typescript": "~2.0.3"
  }
}
src/tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  }
}

参考

7
5
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
7
5