【问题标题】:Why are @HostBinding, @HostListener, and @Input not working in my Angular app?为什么 @HostBinding、@HostListener 和 @Input 在我的 Angular 应用程序中不起作用?
【发布时间】:2018-05-24 13:14:16
【问题描述】:

我无法合并@HostBinding、@HostListener 和@Input。当您将鼠标悬停在图像区域上并悬停在图像区域之外时,它应该在图像之间交换。似乎它应该工作,但它没有。任何帮助表示赞赏。

这是免费且评价很高的书“Angular 4:从理论到实践”,您可以从亚马逊下载。这是“自定义指令”一章的“章节结束”活动。

这是我目前遇到问题的地方的 plunker 链接:http://plnkr.co/edit/MO2m8F4A3PLIIzMIbMD5?p=preview

这里也是代码:

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {
    Component,
    Directive,
    Renderer,
    HostListener,
    HostBinding,
    ElementRef,
    NgModule,
    Input,
    Output,
    EventEmitter
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';


@Directive({
  selector: "[ccRollover]"
})
class RolloverImageDirective {
  constructor(private el: ElementRef, private renderer: Renderer){

  }
  @HostBinding('src') private image: string;

  @Input('ccRollover') images: Object = {
    initial: 'https://unsplash.it/200/300?image=201',
    over: 'https://unsplash.it/200/300?image=202'
  };
  @HostListener('mouseover') onMouseOver() {
    this.image = this.images.over;
  }
  @HostListener('mouseout') onMouseOut(){
    this.image = this.images.initial;
  }
  //TODO: Flesh out this directive
  //TODO: HINT - Use ngOnChanges()
}

@Component({
  selector: 'app',
  template: `
<img ccRollover[images]="{
  initial:'https://unsplash.it/200/300?image=201',
  over:'https://unsplash.it/200/300?image=202'
}"/> 
`
})
class AppComponent {
}

@NgModule({
  imports: [BrowserModule],
  declarations: [
    AppComponent,
    RolloverImageDirective
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

platformBrowserDynamic().bootstrapModule(AppModule);

【问题讨论】:

  • 你想做什么?
  • @yurzui 感谢您提供带有 plunker 链接的工作解决方案。我可以理解您所做的所有更改,除了您合并 HostBinding 的方式。为什么我不能像我尝试的那样直接绑定到字符串变量,而不是通过各种函数?我不明白它是如何知道从解决方案中的 _image 变量绑定的。谢谢。
  • @yurzui 我发现我无法直接看到绑定到字符串变量的原因是因为我没有 HostListener 可以从中进行绑定的初始图像。书中的解决方案使用 'ngOnChanges()' 在页面初始化时初始化初始图像。然后 HostListeners 有一些工作要做。
  • 不过,@yurzui,如果可以的话,请您描述一下您的绑定解决方案是如何工作的,您使用了一个返回 this._image 的函数。因为它让我感到困惑。

标签: angular


【解决方案1】:

  @Input('images') images: Object = {..} //<--images, not  ccRollover 

<img ccRollover [images]="{..} //<--see the "space" between ccRollover and [images]

【讨论】:

  • 我合并了您的两个修改,但仍然无法正常工作。在提交您的想法之前,您可以先尝试一下您的解决方案,方法是转到链接的“plunker”页面。
  • 对不起@Rune,我已经完成并工作了。我刚刚又完成了工作。无论如何,检查yurzui的plunker
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 2021-04-07
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
相关资源
最近更新 更多