Create background-image directive

Asked

Viewed 204 times

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.

1 answer

0

Dude, I currently use this code to put a background on a page... as in your situation, if I don’t find what I want I use a default :

  getMyStyles() {
    const myStyles = {
      'background-image': !this.imgBackground
        ? 'url(\'/assets/images/background/1.png\')'
        : 'url(' + this.imgBackground + ')'
    };
    return myStyles;
  }

And in html you would use this function :

<div [ngStyle]="getMyStyles()">

works perfectly here.

  • 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''.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.