Declare a new color variable ionic 4
In Ionic 4, you can declare a new color variable in the following ways:
Method 1: Using the colors
property in app.component.ts
In your app.component.ts
file, you can add a new color variable to the colors
property:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
colors = {
myNewColor: '#FF69B4' // declare a new color variable
};
}
Method 2: Using a separate colors.ts
file
You can create a separate file called colors.ts
in your project's root directory, and add the new color variable to it:
// colors.ts
export const colors = {
myNewColor: '#FF69B4'
};
Then, in your app.component.ts
file, you can import the colors
object and use the new color variable:
import { Component } from '@angular/core';
import { colors } from './colors';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
constructor() {
console.log(colors.myNewColor); // outputs #FF69B4
}
}
Method 3: Using a theme file
If you're using Ionic's built-in theme system, you can add a new color variable to your theme file (e.g., theme.ios.ts
or theme.md.ts
):
// theme.ios.ts
import { IonicAppTheme } from '@ionic/app-theme';
export const appTheme: IonicAppTheme = {
//...
colors: {
myNewColor: '#FF69B4'
}
};
Then, in your app.component.ts
file, you can inject the theme and use the new color variable:
import { Component } from '@angular/core';
import { appTheme } from './theme.ios';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
constructor() {
console.log(appTheme.colors.myNewColor); // outputs #FF69B4
}
}
Note that in all cases, you can use the new color variable in your CSS files by referencing it using the var()
function, like this:
.my-class {
background-color: var(--myNewColor);
}