ngClassについて
スタイルには、classとstyleの他に、「ngClass」「ngStyle」というものがある。
これはAngular独自のスタイル設定のためのディレクティブである。
今回は3つのチェクボックスをON/OFFするとthin,large,frameの各クラスがON/OFF表示されスタイルが変わるものを作る。
hello.component.html
<divid=“body”>
<h1>{{title}}</h1>
<p
[ngClass]=“noeClass”>ngClass:{{message}}</p>
<inputtype=“checkbox”#ck1 (change)=“check(ck1.checked, ck2.checked, ck3.checked);”>Thin
<inputtype=“checkbox”#ck2 (change)=“check(ck1.checked, ck2.checked, ck3.checked);”>Large
<inputtype=“checkbox”#ck3 (change)=“check(ck1.checked, ck2.checked, ck3.checked);”>Frame
</div>
hello.component.ts
import {Component,OnInit }from‘@angular/core’;
import {Title }from‘@angular/platform-browser’;
@Component({
selector:‘app-hello’,
templateUrl:‘./hello.component.html’,
styleUrls: [‘./hello.component.css’]
})
exportclassHelloComponentimplementsOnInit {
title:string;
message:string;
nowClass:any;
constructor() {
}
ngOnInit() {
this.title =‘Hello-app’;
this.message =‘false,false,false’;
this.nowClass = {
thin:false,
large:false,
frame:false
};
}
check(c1,c2,c3) {
this.nowClass.thin =c1;
this.nowClass.large =c2;
this.nowClass.frame =c3;
this.message =c1 +‘,’ +c2 +‘,’ +c3;
}
}
ngStyleについて
ngClassが、Angular独自のclass属性とするならngStyleはAngular独自のstyleである。
設定するプロパティは、ngClassの場合と同様に、オブジェクトとして値を用意する。
hello.component.html
<divid=“body”>
<h1>{{title}}</h1>
<p
[ngStyle]=“nowStyle”>ngStyle:{{message}}</p>
<inputtype=“text”#in1 (change)=“check(in1.value, in2.value, in3.value);”><br>
<inputtype=“text”#in2 (change)=“check(in1.value, in2.value, in3.value);”><br>
<inputtype=“text”#in3 (change)=“check(in1.value, in2.value, in3.value);”><br>
</div>
hello.component.ts
import {Component,OnInit }from‘@angular/core’;
import {Title }from‘@angular/platform-browser’;
@Component({
selector: ‘app-hello’,
templateUrl: ‘./hello.component.html’,
styleUrls: [‘./hello.component.css’]
})
export classHelloComponentimplementsOnInit {
title:string;
message:string;
nowStyle:any;
constructor() {
}
ngOnInit() {
this.title =‘Hello-app’;
this.message =‘false,false,false’;
this.nowStyle = {
‘border-style’:”,
‘border-width’:”,
‘border-color’:”
};
}
check(in1,in2,in3) {
this.nowStyle[‘border-style’] =in1;
this.nowStyle[‘border-width’]=in2 +‘px’;
this.nowStyle[‘border-color’] =in3;
this.message =JSON.stringify(this.nowStyle);
}
}
コメント