Create policy for background-image

0

I have a directive for images, where if an image does not load I display a default image.

Policy:

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';
  }
}

Usage:

<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 I use background-image .

<figure [ngStyle]="{'background-image': 'url(assets/imgs/teste_344x120-.jpg)'}"></figure>

However, I'm not able to change or adapt the policy I already have to work when background-image does not load.

    
asked by anonymous 04.07.2018 / 16:51

1 answer

0

Now, I use this code to put a background on a page ... as in your situation, if I do not 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.

    
05.07.2018 / 13:32