为什么@HostBinding,@ HotListener和@Input在我的Angular应用程序中不起作用?

时间:2017-12-11 02:40:16

标签: angular

我在整合@HostBinding,@ HotListener和@Input时遇到了麻烦。当您将鼠标悬停在图像区域之外时,它应该在图像之间进行交换。它似乎应该工作,但它没有。任何帮助表示赞赏。

这是来自免费且评价很高的书' Angular 4:From Theory to Practice'你可以从亚马逊下车。这是章节的结尾'关于'自定义指令'。

章节的活动

以下是我目前处理此问题的地方的链接: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);

1 个答案:

答案 0 :(得分:0)

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

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