Angular4-在循环中显示/隐藏内容 [英] Angular4 - show/hide content inside a loop

查看:56
本文介绍了Angular4-在循环中显示/隐藏内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习角度4.我有多个div部分,每个div部分都有按钮和内容,一旦单击了单击的按钮,就会显示相应的div,一旦单击另一个按钮则隐藏其他按钮.

I am started to learn angular 4. I have multiple div section, each div section have button and content, once click the button clicked then will show the respective div, once click another button hide others.

<div *ngFor="let number of [0,1,2,3,4] ; let i = index">
  <div>
    <button (click)="showContent(this);"> Click Me {{index}} </button
    <div class="content"> Hello world {{index}}</div>
  </div>      
</div>

Js代码

export class AppComponent {

  showContent(evt){

    event.target.style.display = 'block';   
  }   

}

对不起,我只添加了最少的代码.

Sorry, I added minimal code only.

推荐答案

有多种方法可以解决此问题:

There are different ways to solve this problem:

1-创建另一个保留每个项目状态的数组,我不喜欢:

1- creating another array that reserves the state of each item, which I don't like :

public state = ['none','none','none','none','none'];  


  <div *ngFor="let number of [0,1,2,3,4] ; let i = index">
    <div>
      <button (click)="state[i]='block'"> Click Me {{index}} </button
      <div [style.display]='state[i]' class="content"> Hello world {{index}}</div>
    </div>      
  </div>

2-创建一个封装逻辑并且可重复使用的指令:

2- Creating a directive that encapsulates the logic and it's reusable :

@Directive({

   selector:`[showHide]`,
   exportAs :'showHide'

})

export class ShowHideDirective{

  @Input('showHide') isHidden = true; // initial state


  public show(){

       this.isHidden = false;
  }



  @HostBinding('[atrr.hidden]') get isItHidden() { // if this is not working for you, you can change it to `[style.display]` and return the `block` or `none`
     return this.isHidden;
  };


}


<div *ngFor="let number of [0,1,2,3,4] ; let i = index">
  <div>
    <button (click)="showHideElement.show()"> Click Me {{index}} </button
    <div #showHideElement='showHide' class="content"> Hello world {{index}}</div>
  </div>      
</div>

别忘了在应用模块中声明 ShowOnClickDirective .

Don't forget to declare ShowOnClickDirective in your app module.

这篇关于Angular4-在循环中显示/隐藏内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆