How to dynamically change static urls in an Angular application in every component
I have an Angular application that I am using alongside a Django application. In Django we have something like this
<img src="{% static 'folder/file.png' %}" />
where we can change the static urls dynamically based on our environment. (Example, I can have static files pointing to my local machine vs I can have them deployed in AWS S3, changing it in one place in the application, will change it everywhere.)
How can I implement something similar in Angular, where I can change the static_url dynamically based on the environment. I would like this to work on all the components within my application.
Example:
When using ng serve it could be <img src="/assets/file.png" />
But when using ng build it would be <img src="https://s3_bucket_url/assets/file.png" />
You can use the environment files, and you can have multiple environments such as prod, dev, local, etc.
// In environment.ts
export const environment = {
production: false,
staticFileUrl: '/assets/'
};
// In environment.prod.ts
export const environment = {
production: true,
staticFileUrl: 'https://s3_bucket_url/assets/'
};
// In environment.local.ts
export const environment = {
production: true,
staticFileUrl: '/assets/'
};
After that you can work with that enviornment in your component
import { Component } from '@angular/core';
import { environment } from '../environments/environment';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
imageUrl: string;
constructor() {
this.imageUrl = `${environment.staticFileUrl}file.png`;
}
}
And work with this.imageUrl inside HTML
<img [src]="imageUrl" />
In the package.json, you can set up custom scripts that can build with a specific environment.
"build:prod": "ng build --configuration production",
"build:dev": "ng build --configuration development",
"build:local": "ng build --configuration local",
And in angular.json,
add the corresponding configuration.
"configurations": {
"production": {},
"development": {},
"local": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.local.ts"
}
]
}
}
There is also an option to have just one environment file, which after building and deploying to the server, may need to be changed in some cases.
In such a case, I recommend adding a config.json to the assets, which should have the exact same structure as the environment, and then using a service, for example: config-service.ts
This method would involve the asynchronous loading of a config.json file and replacing the environment's contents with this configuration. If you were looking for a way to work with the configuration in this manner, I could expand on my response, but this is already unnecessarily long.