Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 640
Nicolas Avatar asked Sep 21 '18 15:09

Nicolas


2 Answers

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;

}
like image 56
Martin Adámek Avatar answered Oct 04 '22 10:10

Martin Adámek


I recently wanted to do the same and I came up with a pipe solution that works in every template without needing to change its .ts file:

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

@Pipe({name: 'env'})
export class EnvPipe implements PipeTransform {
  transform(variable: string): 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}}" />

Make sure to add the pipe component to your app.module.ts

like image 30
Julian Avatar answered Oct 04 '22 10:10

Julian