Dynamically Set background Image in Angular Reusable directive

Umesh Thapa
JavaScript in Plain English
2 min readJan 11, 2023

--

In Angular, you can create a reusable directive that sets the background image of an element dynamically. Here’s an example of how you can create a directive called “setBackgroundImage” that takes an input property called “imageUrl” and sets the background image of the element it’s applied to:

set-background-image-directive.ts

import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[setBackgroundImage]'
})
export class SetBackgroundImageDirective implements OnInit {
@Input() imageUrl:string;
constructor(private elementRef:ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.renderer.setStyle(
this.elementRef.nativeElement,
'backgroundImage',
`url(${this.imageUrl})`
);
}
}

set-background-image-module.ts

import { NgModule } from "@angular/core";
import { SetBackgroundImageDirective } from "./set-background-image.directive";

@NgModule({
declarations: [SetBackgroundImageDirective],
imports: [],
exports:[SetBackgroundImageDirective]
})
export class SetBackgroundImageModule {}

And import in required module

imports: [ CommonModule, SetBackgroundImageModule]

And simply use, like this

<div class="medium" setBackgroundImage [imageUrl]="image">
export class MyComponent {
image: string = 'https://images.pexels.com/photos/14433740/pexels-photo-14433740.jpeg';
}

In this example, the directive uses the ElementRef service to access the DOM element that it’s applied to, and sets the “background-image” style of that element to the value of the `imageUrl` input property.

You can then use this directive in your templates by applying it to elements and binding the “imageUrl” input property to a variable in your component’s class.

It’s important to notice that the directive uses ngOnChanges lifecycle hook, which will be triggered by Angular when an input of the directive is changed.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Build awareness and adoption for your tech startup with Circuit.

--

--

Web Design || Development || Content Creator || Editor || Writer || Ewumesh || Nepal || Australia || USA #ewumesh https://ewumesh.com/