2
votes

I'm having a problem hiding and showing an element in angular 4.

My Html:

<div class='row'>
  <div class='col-md-4 imgTxt' *ngFor="let path of imagePaths" >
    <img [id]='path.id' (mouseenter)="ent(path.img)" class="d-block w-   100 image"  [src]='path.img' alt="Third slide">
    <div class="middle">
      <div class="text">{{path.txt}}</div>
    </div>
  </div>
 </div>

Initially , I want to hide the div(class='middle'). The particular middle div will show when i hover the mover on image.

My ts file: enter image description here

export class SpecialityComponent implements OnInit {
  imagePaths ;
 
  constructor() { 
    this.imagePaths = [
      {id:"a",img:'assets/images/3.JPG',txt:'Breakfast'},
      {id:"b",img:'assets/images/1.JPG',txt:'Lunch'},
      {id:"c",img:'assets/images/2.JPG',txt:'Dinner'},
      {id:"d",img:'assets/images/3.JPG',txt:'Breakfast'},
      {id:"e",img:'assets/images/1.JPG',txt:'Lunch'},
      {id:"f",img:'assets/images/2.JPG',txt:'Dinner'}
    ];
    
  }

ngOnInit() {

}

}

My output: enter image description here

Thanks in advance.

2

2 Answers

0
votes

You should be using a property inside each object to achieve as below,

<div class='row'>
  <div class='col-md-4 imgTxt' *ngFor="let path of imagePaths" >
    <img [id]='path.id' (mouseenter)="ent(path)" class="d-block w-   100 image"  [src]='path.img' alt="Third slide">
    <div class="middle">
      <div class="text" *ngIf="path.showText">{{path.txt}}</div>
    </div>
  </div>
 </div>

Method should look like

ent(path){
    path.showText = true;
}

Note: I have used ngIf to show and hide the text and set the showText property to false as below,

[
      {id:"a",img:'assets/images/3.JPG',txt:'Breakfast', showText:false},
      {id:"b",img:'assets/images/1.JPG',txt:'Lunch', showText:false},
      {id:"c",img:'assets/images/2.JPG',txt:'Dinner', showText:false},
      {id:"d",img:'assets/images/3.JPG',txt:'Breakfast', showText:false},
      {id:"e",img:'assets/images/1.JPG',txt:'Lunch', showText:false},
      {id:"f",img:'assets/images/2.JPG',txt:'Dinner', showText:false},
    ];
1
votes

Try this one. Its working for me.

 <div class='row'>
   <div class='col-md-4 imgTxt' *ngFor="let path of imagePaths;let i = 
    index;" >
    <img [id]='path.id' (mouseenter)="showText = (i+1)" 
     (mouseleave)="showText = 0" class="d-block w-100 
     image"  [src]='path.img' alt="Third slide">
     <div class="middle">
     <div class="text" *ngIf="showText === (i+1)">{{path.txt}}</div>
   </div>
  </div>
</div>

And Your ts file

export class SpecialityComponent implements OnInit {
  showText = 0; // declare this property
}