Nicolas
Nicolas

Reputation: 4756

Using env variables in template files

Is it possible to use env variables in template files?

I'm currently trying this syntax:

<img class="preview-image" src="{{environment.assets + item.image}}" />

which results in the following error:

Identifier 'environment' is not defined. The component declaration, template variable declarations, and element references do not contain such a member

I have tried importing it in my component.ts file, import { environment } from './../../../../environments/environment'; but it didn't change anything.

Upvotes: 14

Views: 10632

Answers (2)

Julian
Julian

Reputation: 341

Solution without changing every .ts component

I really didn't like the idea of changing every .ts component file, so I suggest using a pipe that can be used everywhere in your project:

import {Pipe, PipeTransform} from '@angular/core';
import {environment} from '../environments/environment';

@Pipe({name: 'env'})
export class EnvPipe implements PipeTransform {
  transform(variable: keyof typeof environment): any {
    return environment[variable];
  }
}

Then, in your HTML, just use:

<span>{{'variableName' | env}}</span>

In your case:

<img class="preview-image" src="{{'assets' | env}}{{item.image}}" />

Upvotes: 16

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18359

Just define public environment variable in controller with the value, then you can access it in the template:

import { environment } from '../environments/environment';

export class AppComponent {

  environment = environment;

}

Upvotes: 32

Related Questions