0
I have an image directive, where if an image does not load I display a default image.
Directive:
import { Directive, Input, HostBinding } from '@angular/core';
@Directive({
selector: 'img[default]',
host: {
'(error)':'updateUrl()',
'(load)': 'load()',
'[src]':'src'
}
})
export class ImagePreloadDirective {
@Input() src:string;
@Input() default:string;
@HostBinding('class') className
updateUrl() {
this.src = this.default;
this.className = 'image-default';
}
load(){
//this.className = 'image-default';
}
}
Use:
<img
[src]="'assets/imgs/img-name.png"
default="assets/imgs/image-default.png">
However, I would like to do the same for another situation where background-image
.
<figure [ngStyle]="{'background-image': 'url(assets/imgs/teste_344x120-.jpg)'}"></figure>
However, I am unable to change or adapt the directive I already have to work when the background-image
not carry.
Hello @duardbr, thanks for the reply. But the check you are doing is whether the imgBackground variable has value. In my case, what the above directive does is to check that the image url is valid. For example, even if a URL value exists, it may be that the image does not exist on the server for some reason. In this case, it is returned 'not found 404' and the image is not displayed. The above directive fixes this problem for img elements, but I’m looking for a way to do the same when the image is used as 'background-image''.
– alan