defectivepixel
defectivepixel

Reputation: 615

Import styles from api in Angular

I want to get styles from API and render the component based on that styles.

import { Component } from '@angular/core';
import { StyleService } from "./style.service";
import { Style } from "./models/style";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: [``]
})

export class AppComponent {
  header: boolean;
  footer: boolean;
  style: string;
  constructor(private styleService: StyleService) {}

  ngOnInit() {
    this.logStyles()
  }

  logStyles() {
    this.styleService.getStyles({
      business: 'sekeh'
    })
    .subscribe(
      (val) => {
        this.header = val.header,
        this.footer = val.footer,
        this.style = val.style
      },
      response => {
        console.log("POST call in error", response);
      },
      () => {
        console.log("The POST observable is now completed.");
      });
    }
  }

I have two questions. do i have access to style property in AppComponent class? so i can push new styles to the array. or can i save the api styles in a variable and set styles property to that variable?

Upvotes: 0

Views: 1064

Answers (2)

Bhagwat Tupe
Bhagwat Tupe

Reputation: 1943

You can use NgStyle it updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs

[ngStyle]="customCssProperties"

Here you can pass the properties like

customCssProperties = {
        "padding-top": "5px",
        "margin-left": "5px",
        "color": "red"
      }

Upvotes: 2

IdiakosE Sunday
IdiakosE Sunday

Reputation: 116

You can use [style]="dynamicStyles" which must be Sanitized. That way u can dynamically set styles. More here https://angular.io/api/platform-browser/DomSanitizer

Upvotes: 0

Related Questions