0

Angular 2: Get reference to a directive used in a component

I want to change img src on hover.for reference go through this link:--

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
kapiljain123
  • 159
  • 1
  • 5
  • 15

1 Answers1

3

You can use mouseenter and mouseout on host element as shown below,

Look at working demo : https://plnkr.co/edit/GfgZ46?p=preview

    //our root app component
import {Component, Directive, Output, EventEmitter, Input, SimpleChange} from 'angular2/core'

@Component({
  selector: 'my-app',
  host: {
    '(mouseenter)':'MouseEnter()'
    '(mouseout)':'MouseOut()'
   },
  template: `
    <img [src]="source"/>
    `
})
export class App {
  source='images/angular.png';

  MouseEnter(){
    console.log('Hovering');
    this.source = 'images/car.png';  
  }

  MouseOut(){
    this.source='images/angular.png';
  }
}
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • my HTML:-- is that a correct way to change image source on hover? – kapiljain123 Sep 09 '16 at 10:49
  • what is on-mouseover and on-mouseout? – micronyks Sep 09 '16 at 10:52
  • My Html;-- Component.ts;-- public source='assets/img/{{key}}_inactive.png'; MouseEnter(){ console.log('Hovering'); this.source = 'assets/img/{{key}}_active.png'; } MouseOut(){ console.log('mouseout'); this.source='assets/img/{{key}}_inactive.png'; } but the source is not going to bind and the image is not going to display. – kapiljain123 Sep 09 '16 at 11:08
  • In HTML i give a images [src]="source" and Define the source in component.ts like that public source="assets/img/{{key}}_inactive.png"; but when i am going to display my page for images it shows 404 not found error. How can i solve this. – kapiljain123 Sep 09 '16 at 11:18
  • Which Angular2 version are you using? – micronyks Sep 09 '16 at 11:20
  • can u tell me how to check angular 2 version? one more thing i am using loop to iterate image same image is going to repeat on every div. – kapiljain123 Sep 09 '16 at 11:55
  • check your `package.json` and in there check `dependencies object` and in there check `@angular/core` – micronyks Sep 09 '16 at 12:01
  • "@angular/core": "2.0.0-rc.1", – kapiljain123 Sep 09 '16 at 12:03
  • canu tell me how to isolate child div from parent div angular2? because i am using loop to iterate image and when i am going to hover an image it showing same image on each div – kapiljain123 Sep 09 '16 at 12:09
  • Oh I see. Please show it on plunker with relevant example. – micronyks Sep 09 '16 at 13:00