1

I have an array of colors that I would like to pass to child component.

colors = ['#1e88e5', '#e53935', '#757575'];

I can do it as above with the hardcode hex values, but is there a way that I can use the global variable instead like below.

colors = [$primary, $secondary, $normal];

Since I would like to use the global variable on the component and not on the scss, I am not sure how can I use it.

Any help is appreciated.

Thanks

4
  • You can create a class with the right color, and use the class as string instead of color. Commented Sep 3, 2018 at 7:37
  • Since your colors are called primary, secondary and accent, I assume they won't chang that much when you input them into your components. I would suggest you create a directive for that. Commented Sep 3, 2018 at 8:05
  • @trichetriche I have list of more than 100 color variables and would like to use in .ts file for my charts. Is there a way I can use that global variables in .ts file Commented Sep 4, 2018 at 8:37
  • Then you should definitely group that in a directive. Commented Sep 4, 2018 at 8:45

1 Answer 1

1

You can create class and pass to the child component

here's is an example,

color.ts

export class Color {

  $primary = '#ff0000';
  $secondary = '#ffff00';
}

in app.component.ts

import { Color} from './color';

@Component({
  selector: 'my-app',
  template: `<hello [color]="color"></hello>`
})
export class AppComponent  {
   color = new Color();
}

and in hello.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1 [ngStyle]="{color: color.$primary}">Hello</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  @Input() color: any;

}

here is Stackblitz demo

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the reply. Is there a way that I can use the already existing variable color instead of making the variables again? This isn't what I wanted, instead using already existing variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.