2017-06-03 25 views
0

我想要做的是,當我將鼠標懸停在「點擊我」按鈕,然後它應該顯示在網頁上的圖像,當我unhover它不應該顯示出與鼠標懸停選項的幫助下如何在angularjs2中通過鼠標懸停選項將鼠標懸停在按鈕上,從而將圖像閃爍?

這裏是任何圖像我試圖app.component.ts和my.component.ts做文件

這裏是app.component.ts代碼:

import { Component } from '@angular/core';  //importing components from angular 
import { MyComponent } from './my.component'; //importing components from my.component 



@Component({ 
    selector: 'my-app', 
    template: `<h1> Hi Buddy!! </h1> 
      <mytag></mytag>`, 
    directives: [MyComponent]   //adding directives from mycomponents 
}) 
export class AppComponent { } 

這裏是my.component的代碼。 ts:

import { Component } from "@angular/core"; 

@Component({ 
     selector:'mytag', 
     template: `<button (mouseover)="<img [src]="image"> " >click me</button>` // here i tried to flash image by hovering 
}) 
export class MyComponent{ 
     public image="http://lorempixel.com/400/200"; 
     myclick(klm){ 
      console.log(klm); 

    } 
} 

因此,我應該在my.component.ts的類或元數據中進行哪些更改才能做到這一點

回答

0

您可以使用Angular Animations模塊來實現相同。

做下面的更改您的MyComponent的:

import { Component } from '@angular/core' 
import { trigger, state, style, transition, animate, keyframes, group } from '@angular/animations'; 
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 

@Component({ 
     selector:'mytag', 
     template: `<button (mouseover)="toggleOnOff()">click me</button> 
        <img [src]="image" [@switchImageDisplay]="showImage"/> 
        ` 
     , 
     animations: [ 
     trigger("switchImageDisplay",[ 
      state("show", style({ 
      display : 'block' 
      })), 
      state("hide", style({ 
      display : 'none' 
      })), 
      transition('show <-> hide',[animate('0s')]), 
     ]) 

     ] 
    }) 
export class SwitchDisplayComponent { 
     public image="http://lorempixel.com/400/200"; 
     public showImage : string; 
      toggleOnOff(){ 
      console.log("Previous display value is",this.showImage); 
       this.showImage = (this.showImage === "show") ? "hide" : "show"; 
       console.log("Current display value is",this.showImage); 
     } 

} 

說明: toggleOnOff()函數將一個字符串變量showImage的顯示和隱藏。 在動畫中,我們創建一個觸發器併爲其命名。在我們的例子中,我們將其命名爲「switchImageDisplay」。我們在動畫觸發器中聲明瞭兩個狀態,分別是「顯示」和「隱藏」。在這些狀態下,我們定義了要使用的CSS。最後,我們定義了一個轉換,它是2種綁定方式,並在0秒內執行。如果你想在一段時間內隱藏圖像增加時間。

在模板代碼中,我們使用代碼[@switchImageDisplay] =「showImage」將img標籤綁定到動畫。基於「showImage」值,定義了動畫「switchImageDisplay」的狀態。

從'@ angular/platform-b​​rowser/animations'導入導入{BrowserAnimationsModule};在你的app.module.ts和imports數組中。