typescript 在角度 4 中显示一个 div 并隐藏另一个 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51797741/
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
Show one div and hide another div in angular 4
提问by vedankita kumbhar
I want show one element on button click and hide another element on same button click. Here is my code
我想在单击按钮时显示一个元素并在单击同一按钮时隐藏另一个元素。这是我的代码
I am able to show sub div but I want to hide that element which contain "show sub content" button on same button click. Please help.
我能够显示子 div,但我想隐藏包含“显示子内容”按钮的同一按钮单击的元素。请帮忙。
回答by Sivakumar Tadisetti
You can do like below with single function, working example is here on the Stackblitz
您可以使用单个功能执行以下操作,工作示例在Stackblitz 上
In the component file
在组件文件中
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
showMainContent: Boolean = true;
constructor() {}
ShowHideButton() {
this.showMainContent = this.showMainContent ? false : true;
}
}
And in the template file
并在模板文件中
<div *ngIf="!showMainContent">
<button (click)="ShowHideButton()">Show Sub content</button>
My Main content
</div>
<div *ngIf="showMainContent">
Sub Content
<button (click)="ShowHideButton()">Show Main Content</button>
</div>
回答by Lazar Ljubenovi?
Determine whether to show or hide based on the current state. If it's currently true
, then make it false
. If it's currently false
, then make it true
.
根据当前状态决定是显示还是隐藏。如果它是 current true
,那么 make it false
。如果它是 current false
,那么 make it true
。
ToggleButton() {
this.showSelected = !this.showSelected;
}
Here's the demo.
这是演示。
回答by Sanoj_V
You can also do it like this way. No need to initialize showMainContentvariable.
你也可以这样做。无需初始化showMainContent变量。
<div *ngIf="!showMainContent">
<button (click)="showMainContent=!showMainContent">Show Sub content</button>
My Main content
</div>
<div *ngIf="showMainContent">
Sub Content
<button (click)="showMainContent=!showMainContent">Show Main Content</button>
</div>
回答by Sven
Just reasign the variable with the opposite value of it
只需使用它的相反值重新分配变量
ShowButton() {
this.showSelected = !this.showSelected;
}
回答by Sajeetharan
回答by fedexo
Instead of writing ngIf for n time, you could also write ngIf else:
除了写 n 次 ngIf,你还可以写 ngIf else:
<div *ngIf="isLoggedIn; else loggedOut">
Welcome back, friend.
</div>
<ng-template #loggedOut>
Please friend, login.
</ng-template>
or ngIf else then syntax:
或 ngIf else then 语法:
<ng-container
*ngIf="isLoggedIn; then loggedIn; else loggedOut">
</ng-container>
<ng-template #loggedIn>
<div>
Welcome back, friend.
</div>
</ng-template>
<ng-template #loggedOut>
<div>
Please friend, login.
</div>
</ng-template>
The choice depends in how many check you need to do.
选择取决于您需要进行多少次检查。