【发布时间】:2018-09-13 16:53:56
【问题描述】:
有没有办法用 x 按钮关闭 div?在这种情况下,div 是一个“通知”,它会出现几秒钟然后消失。我不想使用隐藏,因为显然 div 永远不会出现。
【问题讨论】:
-
对于 Angular 2+,你见过this answer
-
嗯,不,我认为没有办法用 X 按钮关闭 div,抱歉。
有没有办法用 x 按钮关闭 div?在这种情况下,div 是一个“通知”,它会出现几秒钟然后消失。我不想使用隐藏,因为显然 div 永远不会出现。
【问题讨论】:
您可以使用 *ngIf 结构指令根据布尔值呈现 div。您需要做的是更改按钮单击时的布尔值。
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public showNotification: boolean;
constructor() {
this.showNotification = true;
setInterval(() => {
this.showNotification = true;
}, 3000);
}
public onCloseClick(): void {
this.showNotification = false;
}
}
app.component.html
<div>
<div class="notification" *ngIf="showNotification">
<div class="close" (click)="onCloseClick()">x</div>
<div class="content">
Some content
</div>
</div>
</div>
我假设 showNotification 变量是从服务或其他东西更新的。这就是为什么我使用 setTimeInterval 来更新 showNotifications 变量的值。
【讨论】:
也许你可以在你的 html 标签中使用布尔值和 *ngIf ?因此每次你想切换它。
这是一个小例子
<button type="button" (click)="visible = false" >x</button>
<div *ngIf="visible">
<!-- rest of your html tags here -->
</div>
你的组件:
export class YourComponent{
visible:boolean = true;
}
【讨论】: