Html Angular 2 - 单击以显示和隐藏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43544910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:35:21  来源:igfitidea点击:

Angular 2 - Click to show and hide

htmlangular

提问by pPeter

I want to use a button to show and hide elements in my HTML. I know i have to use a boolean in the typescript and *ngIf in the HTML.

我想使用一个按钮来显示和隐藏 HTML 中的元素。我知道我必须在打字稿中使用布尔值,在 HTML 中使用 *ngIf。

In my typescript i have a boolean:

在我的打字稿中,我有一个布尔值:

showHide: false;

In my HTML i have:

在我的 HTML 中,我有:

<button (click) = "showHide=true" </button>

I use this to hide elements. I hide my elements with the use of *ngIf="showHide" on the elements i want to hide.

我用它来隐藏元素。我在要隐藏的元素上使用 *ngIf="showHide" 来隐藏我的元素。

But how can i bring back the elements i have hidden with the same button?

但是我怎样才能恢复我用同一个按钮隐藏的元素?

回答by Tiep Phan

try this

尝试这个

<button (click)="showHide = !showHide">click</button>

回答by coreuter

You could use a function to change from true to false and vice versa instead of just setting showHidetrue each time you click the button.

您可以使用函数从 true 更改为 false,反之亦然,而不是每次单击按钮时都设置showHidetrue。

To do so you need to create a function e.g. changeShowStatusto change the value of showHide.

要做到这一点,你需要创建一个函数如changeShowStatus改变的值显示隐藏

changeShowStatus(){
    this.showHide = !this.showHide;
  }

Then you call this function every time you hit the button by changing your showHide=true to changeShowStatus():

然后您每次点击按钮时都会调用此函数,方法是将 showHide=true 更改为 changeShowStatus():

<button type="button" (click)="changeShowStatus()">show/hide</button>

To set the initial status you could set the showHidevalue in the constructor and define showHide just as boolean:

要设置初始状态,您可以在构造函数中设置showHide值并将 showHide 定义为布尔值:

export class App {
  ...
  showHide: boolean;

  constructor() {
    this.showHide = true;
  }
  ...
}

Plunker: show/hide div with TS/Angular2

Plunker:使用 TS/Angular2 显示/隐藏 div