Angular 2에서 동적으로 CSS 업데이트
예를 들어 Angular2 구성 요소가 있다고 가정해 보겠습니다.
//home.component.ts
import { Component } from 'angular2/core';
@Component({
selector: "home",
templateUrl: "app/components/templates/home.component.html",
styleUrls: ["app/components/styles/home.component.css"]
})
export class HomeComponent {
public width: Number;
public height: Number;
}
이 구성 요소의 템플릿 html 파일
//home.component.html
<div class="home-component">Some stuff in this div</div>
그리고 마지막으로 이 구성 요소에 대한 css 파일.
//home.component.css
.home-component{
background-color: red;
width: 50px;
height: 50px;
}
보시다시피 클래스에는 2개의 속성이 있습니다.width
그리고.height
너비와 높이에 대한 CSS 스타일이 너비와 높이 속성의 값과 일치하고 속성이 업데이트되면 div의 너비와 높이가 업데이트되면 좋겠습니다.이것을 달성하기 위한 적절한 방법은 무엇입니까?
사용해 보세요.
<div class="home-component"
[style.width.px]="width"
[style.height.px]="height">Some stuff in this div</div>
[업데이트]:%로 설정하려면 사용
[style.height.%]="height">Some stuff in this div</div>
@Gaurav의 답변과 함께 px 또는 em 대신 %를 사용하는 것은 단지
<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>
이렇게 하면 됩니다.
<div class="home-component"
[style.width]="width + 'px'"
[style.height]="height + 'px'">Some stuff in this div</div>
호스트 바인딩을 사용할 수도 있습니다.
import { HostBinding } from '@angular/core';
export class HomeComponent {
@HostBinding('style.width') width: Number;
@HostBinding('style.height') height: Number;
}
홈 구성요소 내에서 너비 또는 높이 속성을 변경할 경우 스타일 속성에 영향을 미칩니다.
{{} 대신 [] 가새를 사용하여 변수를 사용하여 동적으로 너비를 설정하려면:
<div [style.width.px]="[widthVal]" [style.height.px]="[heightVal]"></div>
<div [style.width.%]="[widthVal]" [style.height.%]="[heightVal]"></div>
승인된 답변은 올바르지 않습니다.
그룹화된 스타일의 경우 ngStyle 디렉티브를 사용할 수도 있습니다.
<some-element [ngStyle]="{'font-style': styleExpression, 'font-weight': 12}">...</some-element>
공식 문서는 여기에 있습니다.
import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';
import {Directive, ElementRef, Renderer, Input,ViewChild,AfterViewInit} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<style>
.myStyle{
width:200px;
height:100px;
border:1px solid;
margin-top:20px;
background:gray;
text-align:center;
}
</style>
<div [class.myStyle]="my" [style.background-color]="randomColor" [style.width]="width+'px'" [style.height]="height+'px'"> my width={{width}} & height={{height}}</div>
`,
directives: []
})
export class AppComponent {
my:boolean=true;
width:number=200px;
height:number=100px;
randomColor;
randomNumber;
intervalId;
textArray = [
'blue',
'green',
'yellow',
'orange',
'pink'
];
constructor()
{
this.start();
}
start()
{
this.randomNumber = Math.floor(Math.random()*this.textArray.length);
this.randomColor=this.textArray[this.randomNumber];
console.log('start' + this.randomNumber);
this.intervalId = setInterval(()=>{
this.width=this.width+20;
this.height=this.height+10;
console.log(this.width +" "+ this.height)
if(this.width==300)
{
this.stop();
}
}, 1000);
}
stop()
{
console.log('stop');
clearInterval(this.intervalId);
this.width=200;
this.height=100;
this.start();
}
}
bootstrap(AppComponent, []);
인라인 [style]에 동적 값을 추가하여 div의 스타일(폭 및 높이)을 동적으로 변경할 수 있습니다.폭] 및 [스타일]을 선택합니다.div의 높은[높은] 성질
이 경우 HomeComponent 클래스의 너비 및 높이 속성을 div의 인라인 스타일 너비 및 높이 속성과 함께 바인딩할 수 있습니다.사사의 지시대로
<div class="home-component"
[style.width]="width + 'px'"
[style.height]="height + 'px'">Some stuff in this div
</div>
작업 데모의 경우 이 플런커(http://plnkr.co/edit/cUbbo2?p=preview) 를 참조하십시오.
//our root app component
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES,FormBuilder,AbstractControl,ControlGroup,} from "angular2/common";
@Component({
selector: 'home',
providers: [],
template: `
<div class="home-component" [style.width]="width+'px'" [style.height]="height+'px'">Some this div</div>
<br/>
<form [ngFormModel]="testForm">
width:<input type="number" [ngFormControl]="txtWidth"/> <br>
Height:<input type="number"[ngFormControl]="txtHeight" />
</form>
`,
styles:[`
.home-component{
background-color: red;
width: 50px;
height: 50px;
}
`],
directives: [FORM_DIRECTIVES]
})
export class App {
testForm:ControlGroup;
public width: Number;
public height: Number;
public txtWidth:AbstractControl;
public txtHeight:AbstractControl;
constructor(private _fb:FormBuilder) {
this.testForm=_fb.group({
'txtWidth':['50'],
'txtHeight':['50']
});
this.txtWidth=this.testForm.controls['txtWidth'];
this.txtHeight=this.testForm.controls['txtHeight'];
this.txtWidth.valueChanges.subscribe(val=>this.width=val);
this.txtHeight.valueChanges.subscribe(val=>this.height =val);
}
}
위의 답변은 모두 훌륭합니다.하지만 만약 당신이 아래의 html 파일을 바꾸지 않는 해결책을 찾으려 한다면 도움이 됩니다.
ngAfterViewChecked(){
this.renderer.setElementStyle(targetItem.nativeElement, 'height', textHeight+"px");
}
렌더러를 가져올 수 있습니다.import {Renderer} from '@angular/core';
Wenhao Wu의 모습이 좋았습니다.위의 생각입니다만, 디브와 클래스를 식별해야 했습니다. .ui-tree
PrimeNG 트리 구성 요소에서 높이를 동적으로 설정합니다.내가 찾을 수 있는 모든 답은 다음을 사용할 수 있도록 div 이름(즉, #treediv)을 지정해야 합니다.@ViewChild()
,@ViewChildren()
,@ContentChild()
,@ContentChilden()
기타. 이 작업은 타사 구성 요소로 인해 지저분했습니다.
마침내 귄터 외흐바우어의 토막글을 발견했습니다.
ngAfterViewInit() {
this.elRef.nativeElement.querySelector('.myClass');
}
이를 통해 다음과 같은 이점을 얻을 수 있었습니다.
@Input() height: number;
treeheight: number = 400; //default value
constructor(private renderer: Renderer2, private elRef: ElementRef) { }
ngOnInit() {
this.loading = true;
if (this.height != null) {
this.treeheight = this.height;
}
}
ngAfterViewInit() {
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.ui-tree'), 'height', this.treeheight + "px");
}
함수도 호출하여 이를 달성할 수 있습니다.
<div [style.width.px]="getCustomeWidth()"></div>
getCustomeWidth() {
//do what ever you want here
return customeWidth;
}
HTML에서:
<div [style.maxHeight]="maxHeightForScrollContainer + 'px'">
</div>
인 Ts
this.maxHeightForScrollContainer = 200 //your custom maxheight
나의 해결책은 다음의 조합이었습니다.@ViewChild()
그리고.ngAfterViewInit()
기능.
HTML:
<div
class="form-field text-form-field"
#textInputContainer
>
<label *ngIf="field?.label"> My Label </label>
<input type="text"/>
</div>
TS:
@ViewChild("textInputContainer") textInputContainer;
constructor() {}
ngOnInit(): void {}
ngAfterViewInit(): void {
this.textInputContainer.nativeElement.style.width = "50%";
}
언급URL : https://stackoverflow.com/questions/35882670/dynamically-updating-css-in-angular-2
'programing' 카테고리의 다른 글
입력 파일이 텍스트 형식 덤프인 것 같습니다.psql을 사용하십시오. (0) | 2023.05.11 |
---|---|
에 대한 링커 상태.NET 앱("Please Sir, May I have a Linker" 2009년판) (0) | 2023.05.11 |
Mongo DB - 독립 실행형 및 1노드 복제본 세트의 차이점 (0) | 2023.05.11 |
프로젝트를 Angular v5에서 Angular v6로 업그레이드하려고 합니다. (0) | 2023.05.11 |
Xcode 프로젝트를 위해 포드 파일에 여러 대상을 지정하려면 어떻게 해야 합니까? (0) | 2023.05.11 |