简体   繁体   中英

Is it possible to use styles from an Angular service in scss?

I have a change-color.service.ts that has the following:

public defaultStyles = {
    firstDesignBackgroundColor: '#a31329',
    firstDesignFontColor: '#ffffff',
    secondDesignBackgroundColor: '#d1cfcfff',
    secondDesignFontColor: '#000000'
  };

now I will like to add to my style.scss for the statement

:host ::ng-deep th span#optimize-checkbox-header .mat-checkbox label.mat-checkbox-layout .mat-checkbox-inner-container.mat-checkbox-inner-container-no-side-margin .mat-checkbox-frame {
  border: 2px solid #fff !important;
}

replace the #fff with firstDesignFontColor from the change-service . Do you know how I can create this dependency? Is this possible at all?

There is actually a way to realize it with css variables that I will post here as a second answer.

You can change css variables from JavaScript code, so if you use variables for your class like this simplified example:

:root {
  --bg-color: red;
}

.test {
  background-color: var(--bg-color);
}

then you can change this from your ChangeColorService

interface Colors {
  background: string;
}

@Injectable()
export class ChangeColorService {
    colors$ = new BehaviorSubject<Colors>({ background: 'red' });

    constructor(@Inject(DOCUMENT) private document: Document) { }

    change(colors: Colors) {
      const root = this.document.documentElement;
      root.style.setProperty('--bg-color', colors.background);
      this.colors$.next(colors);
    }
}

Full example: https://stackblitz.com/edit/angular-change-css-variable?file=src/app/app.component.ts

No that's not possible. What is possible, is to use style bindings.

class YourComponent {
    styles: any;
    constructor(private color: ChangeColor) {}
    ngOnInit() { this.styles = this.color.defaultStyles; }
}
  <div [style.background-color]="styles.firstDesignBackgroundColor"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM