【问题标题】:Angular (load) on a background-image背景图像上的角度(负载)
【发布时间】:2018-09-26 03:21:59
【问题描述】:

我正在使用 Angular 5,我正在尝试在加载 div 的背景图像时获取加载图标。
如果它是正常的img,我对此没有任何问题,但如果我尝试将它作为背景,它就不起作用。

这里是一些示例代码

app.component.html

<div class="test" [someDirective]="'some/otherImg.jpg'"></div>  
<img class="test" [someDirective]="'some/OtherImg.jpg'">

app.component.css

.test{
  width: 300px;
  height: 200px;
}

some.directive.ts

import { Directive, ViewChild, Input, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[someDirective]'
})
export class SomeDirective {
  @Input() someDirective:string;

  constructor(private element:ElementRef){
    element.nativeElement.src = 'some/imgUrl.gif';
    element.nativeElement.style = "background-image: url('some/imgUrl.gif')";
  } 

  @HostListener('load', ['$event'])
  onLoad() {
    this.element.nativeElement.src = "some/otherImg.jpg";
    this.element.nativeElement.style = "background-image: url('some/otherImg.jpg')";
  }
}  

有没有办法让它工作,以便背景也以与普通图像相同的方式加载?

我应该提到,让加载 gif 充当背景图像没有问题,它工作正常但不会改变。

【问题讨论】:

  • 尝试写一个绝对网址...我的意思是../some/img.jpg
  • 我的错我应该更具体地解决这个问题。网址不是问题。它们只是示例而不是真正的网址。在制作示例时我应该多加注意......对不起
  • 的加载图标和图像工作正常,它只是
    ,它的背景图像会导致问题,因为看起来 (load) 只检查内容是否已加载并且不是风格
  • 你没有关闭图片标签 / 丢失了
  • 你找到解决办法了吗?

标签: angular typescript


【解决方案1】:

不要直接操作ElementRef。使用Renderer 类。用 observables 试试这个实现。就像提到的 zmanc 一样,您不能使用 background-url 技术。坚持使用src 属性。

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

import { fromEvent } from 'rxjs/observable/fromEvent';
import { first } from 'rxjs/operators';

@Directive({
  selector: '[load]',
})
export class LoadImageDirective {
  constructor(private renderer: Renderer2, private el: ElementRef) { }

  ngOnInit() {
    fromEvent(this.el.nativeElement, 'load')
      .pipe(first())
      .subscribe(() => this.setImage())

    this.setPlaceholder();

  }

  private setPlaceholder() {
    this.renderer.setAttribute(
      this.el.nativeElement,
      'src', `https://via.placeholder.com/50x50`
    )
  }


  private setImage = () => {
    this.renderer.setAttribute(
      this.el.nativeElement,
      'src', `https://http.cat/400`
    )
  }
}

Live demo

【讨论】:

    【解决方案2】:

    这没有按预期工作的原因是 CSS 加载没有触发 DOM 加载事件。经过一些研究,似乎人们解决这个问题的方式(甚至在 Angular 之外)是将图像加载到隐藏的 img 元素中并使用它来触发事件。它非常混乱,但这似乎是最好的方法。

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签