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.
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With