Angular2 동적 변경 CSS 속성
우리는 Angular2 애플리케이션을 만들고 있으며 어떻게든 글로벌 CSS 변수를 만들 수 있기를 원합니다(그리고 변수가 할당될 때마다 변경될 때마다 속성 값을 업데이트합니다).
우리는 한동안 Polymer를 사용했고(지금은 Angular2 구성 요소로 전환하고 있습니다) CSS 속성을 사용했습니다(Polymer는 일부 폴리필을 가지고 있습니다). 우리는 다음을 사용하여 스타일을 업데이트했습니다.Polymer.updateStyles()
.
우리가 비슷한 기능을 할 수 있는 방법이 있습니까?
편집:
우리는 Sass와 비슷한 것을 원합니다.color: $g-main-color
또는 CSS 사용자 지정 속성으로color: var(--g-main-color)
그리고 우리가 재산의 가치를 바꾸기로 결정할 때마다, 예를 들어, 비슷한 것.updateVariable('g-main-color', '#112a4f')
모든 곳에서 동적으로 값을 업데이트합니다.앱이 실행되는 동안 이 모든 것.
편집 2:
나는 내 CSS의 다른 부분(호스트, 하위 요소...)에서 일부 글로벌 CSS 변수를 사용하여 값을 즉시 변경할 수 있기를 원합니다. 따라서 내 색상 변수를 변경하면 앱의 모든 곳에서 변경됩니다.
예를 들어 Sass 구문을 사용합니다.
:host { border: 2px solid $my-color }
:host .some-label { color: $my-color }
앵귤러 파이프 같은 것을 사용할 수 있습니까? (그러나 HTML에서만 작동하는 것으로 추정됩니다.)
:host { border: 2px solid {{ 'my-color' | cssvariable }} }
:host .some-label { color: {{ 'my-color' | cssvariable }} }
인라인 스타일 사용
<div [style.color]="myDynamicColor">
여러 CSS 클래스 매핑을 사용하여 원하는 것으로 매핑하고 다음과 같은 클래스를 전환합니다.
/* CSS */
.theme { /* any shared styles */ }
.theme.blue { color: blue; }
.theme.red { color: red; }
/* Template */
<div class="theme" [ngClass]="{blue: isBlue, red: isRed}">
<div class="theme" [class.blue]="isBlue">
코드 샘플 출처: https://angular.io/cheatsheet
nongClass 디렉티브에 대한 자세한 내용은 https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html 에서 확인할 수 있습니다.
표준 CSS 변수를 사용하면 됩니다.
글로벌 CSS(예: styles.css)
body {
--my-var: #000
}
구성 요소의 CSS 또는 무엇이든:
span {
color: var(--my-var)
}
그런 다음 인라인 스타일을 html 요소로 설정하여 TS/JS로 직접 변수 값을 변경할 수 있습니다.
document.querySelector("body").style.cssText = "--my-var: #000";
그렇지 않으면 jQuery를 사용할 수 있습니다.
$("body").css("--my-var", "#fff");
당신은 어떤 예시 코드도 가지고 있지 않지만, 제 생각에 당신은 이런 것을 하고 싶은 것 같습니다.
@View({
directives: [NgClass],
styles: [`
.${TodoModel.COMPLETED} {
text-decoration: line-through;
}
.${TodoModel.STARTED} {
color: green;
}
`],
template: `<div>
<span [ng-class]="todo.status" >{{todo.title}}</span>
<button (click)="todo.toggle()" >Toggle status</button>
</div>`
})
사용자가 지정합니다.ng-class
동적 변수(모델의 속성)에 대한TodoModel
짐작하시겠지만)
todo.toggle()
의 가치를 변화시키고 있습니다.todo.status
입력의 클래스가 변화하고 있습니다.
이것은 클래스 이름에 대한 예이지만 실제로는 CSS 속성에 대해서도 같은 생각을 할 수 있습니다.
이것이 당신이 말한 것이기를 바랍니다.
이 예는 여기에 있는 훌륭한 에그헤드 튜토리얼을 위해 취해진 것입니다.
저는 당신이 원하는 것을 할 수 있는 한 가지 방법을 탐구하기 위해 이 플랭크를 했습니다.
알겠습니다mystyle
상위 구성 요소에서 가져오지만 서비스에서 가져올 수 있습니다.
import {Component, View} from 'angular2/angular2'
@Component({
selector: '[my-person]',
inputs: [
'name',
'mystyle: customstyle'
],
host: {
'[style.backgroundColor]': 'mystyle.backgroundColor'
}
})
@View({
template: `My Person Component: {{ name }}`
})
export class Person {}
Angular 6 + Alyle UI
Alyle UI를 사용하여 스타일을 동적으로 변경할 수 있습니다.
여기 데모 스택 블리츠가 있습니다.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
CommonModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
AlyleUIModule.forRoot(
{
name: 'myTheme',
primary: {
default: '#00bcd4'
},
accent: {
default: '#ff4081'
},
scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
lightGreen: '#8bc34a',
colorSchemes: {
light: {
myColor: 'teal',
},
dark: {
myColor: '#FF923D'
},
myCustomScheme: {
background: {
primary: '#dde4e6',
},
text: {
default: '#fff'
},
myColor: '#C362FF'
}
}
}
),
LyCommonModule, // for bg, color, raised and others
],
bootstrap: [AppComponent]
})
export class AppModule { }
HTML
<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>
스타일 변경용
import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';
@Component({ ... })
export class AppComponent {
classes = {
card: this.theme.setStyle(
'card', // key
() => (
// style
`background-color: ${this.theme.palette.myColor};` +
`position: relative;` +
`margin: 1em;` +
`text-align: center;`
...
)
)
}
constructor(
public theme: LyTheme
) { }
changeScheme() {
const scheme = this.theme.palette.scheme === 'light' ?
'dark' : this.theme.palette.scheme === 'dark' ?
'myCustomScheme' : 'light';
this.theme.setScheme(scheme);
}
}
언급URL : https://stackoverflow.com/questions/33328347/angular2-dynamic-change-css-property
'sourcecode' 카테고리의 다른 글
비'@objc' 메서드가 '@objc' 프로토콜의 선택적 요구 사항을 충족하지 않습니다. (0) | 2023.09.01 |
---|---|
웹 워커로부터 AJAX 요청을 할 수 있습니까? (0) | 2023.09.01 |
평평하지 않은 인덱스를 반환하는 numpy 배열의 Argmax (0) | 2023.09.01 |
Javascript에서 이중 백슬래시를 단일 백슬래시로 바꾸기 (0) | 2023.09.01 |
Jersey: 요소가 1개인 Json 배열이 개체로 직렬화됩니다. (0) | 2023.09.01 |