Angular指令:悬停时动态更改img背景

问题描述 投票:0回答:2

[看截图,我有一个页面的背景图片,下面有两个缩略图。我希望能够在鼠标悬停缩略图时将页面的background图像更改为缩略图的图像。

下面是我的指令。我可以获取缩略图的src,但对于如何将其注入到元素中以至于页面背景发生变化,我深感困惑。另外,我已经从Expected 2 arguments, but got 1.行中收到了错误ViewChild

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

@Directive({
  selector: '[dynamicBackgroundImg]'
})
export class DynamicBackgroundImgDirective {
  thumbSRC : string;
  @ViewChild('tourBackgroundImg') tourBackgroundImg:ElementRef;


  constructor(private el: ElementRef) {}

  @HostListener('mouseover') onMouseOver() {
    this.ChangeBackgroundImg();
  }

  @HostListener('mouseleave') onMouseLeave() {

  }

  ChangeBackgroundImg() {
    this.thumbSRC = this.el.nativeElement.getAttribute('src');
    alert(this.thumbSRC);
    this.tourBackgroundImg.nativeElement.setAttribute(this.thumbImgSrc);
  }

}

这是我的HTML的缩小版本:

<section class="tours-section" [ngClass]="{ 'load-complete' : viewPage }">
  <img class="component-loader" src="../../../assets/icons/loading.svg">
  <div class="tours-wrapper">
    <div class="tours-right page-title">
      <p>{{pageTitle}}</p>
      <picture>
        <source srcset="{{ toursImageUrl }}?fm=webp" type="image/webp">
        <source srcset="{{ toursImageUrl }}?fm=png" type="image/png">
         <!-- Here is the tag that sets the background img of the page, when one hover over the thumnail, this needs to change, the src of the thumb needs to be injected here. -->
        <img src="{{ toursImageUrl }}?fm=png" alt="{{ toursImageAlt }}" (load)="imageLoaded()" class="section-background" tourBackgroundImg>
      </picture>
    </div>
    <div class="tours-left">
        <div class="tours-thumbs">
          <div class="tours-container">
            <!-- Ideally when one hovers over the thumnail, it would get the src of the tour-image -->
            <figure class="tour-image-small">
              <picture>
                <img src="assets/images/L1000433-min.JPG" alt="" dynamicBackgroundImg>
                <figcaption></figcaption>
              </picture>
            </figure>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

下面是一个屏幕快照,希望可以帮助您了解我要实现的目标:

enter image description here

可能是我错误地处理了整件事,感谢您的任何投入。

angular typescript angular-directive
2个回答
0
投票
这里是代码:

html:

<div class="app-component"> <h1>App Component</h1> hover this image to change the background:<br> <img #myImage src="https://picsum.photos/200/300"/> </div>

css(只需设置要更改的图像):

.app-component{
  background-image: url("https://img.maxisciences.com/s3/frgsd/1024/coronavirus/default_2020-02-28_2bbef01b-f63a-4a59-b31e-788da4e402bb.jpeg");
}

和TS:

import {
  Component,
  OnInit,
  ElementRef,
  ViewChild,
  Renderer2,
AfterViewInit
} from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
  @ViewChild("myImage") myImage: ElementRef;
  globalInstance: any;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {

    this.globalInstance = this.renderer.listen(
      this.myImage.nativeElement,
      "mouseover",
      () => {
        this.renderer.setStyle(
          document.body.querySelector('.app-component'),
          "background-image",
          `url(${this.myImage.nativeElement.src})`
        );
      }
    );
  }
}

如您所见,其想法是绑定并监听图像上的事件(此处为'mouseover'事件),并在触发时更改目标的背景(此处为appComponent)。


0
投票
以下代码应该起作用:

import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[dynamicBackgroundImg]' }) export class DynamicBackgroundImgDirective { // use the @Input to pass the src image @Input() thumbSRC : string; constructor(private el: ElementRef, private renderer) {} @HostListener('mouseover') onMouseOver() { this.ChangeBackgroundImg(); } @HostListener('mouseleave') onMouseLeave() { } ChangeBackgroundImg() { // use the Renderer2 service to set the attribute this.renderer.setAttribute(this.element.nativeElement, 'src', thumbSRC); } }

在组件模板中:

<- add a template variable for the image that you want to display it ->
<img src="{{ toursImageUrl }}?fm=png" alt="{{ toursImageAlt }}" (load)="imageLoaded()" class="section-background" #tourBackgroundImg>

....

<- bind the src image ->
<img src="assets/images/L1000433-min.JPG" dynamicBackgroundImg [thumbSRC]="tourBackgroundImg.src">

ViewChild行中的错误Expected 2 arguments, but got 1使我相信您正在使用Angular8。如果是这样,则需要像这样传递@ViewChild中的配置对象:

@ViewChild('element', { static: false })

如果在OnInit生命周期挂钩中使用,则static属性必须为true,否则为false。在以前的版本以及Angular 9中,第二个参数现在是可选的,除非ngOnInit中未使用它。

© www.soinside.com 2019 - 2024. All rights reserved.