![](/img/trans.png)
[英]I want to make an element display when a button is pressed. by default the element is shown, how do I make it display none by default?
[英]How to make the element `display: none` by clicking the button
我想實現一個在使用Angular 2構建的應用程序中單擊按鈕時隱藏元素的功能。
<div *ngFor="let todo of todos" class="col-sm-8 col-sm-offset-2">
<div class="panel panel-default step"> // from here
<div class="panel-body">
<a [routerLink]="['/todo', todo.id]">{{todo.title}}</a>
<button (click)="delete(todo.id)" type="button" class="btn btn-success btn-circle pull-right"><i class="glyphicon glyphicon-ok"></i></button>
</div>
</div>//so far
</div>
我想知道當使用以上代碼單擊按鈕時如何使待辦事項消失。 盡管這是一個基本問題,但請教。
您應該按以下方式刪除待辦事項
delete(id:number){
this.todos.splice(id,1)
}
我認為這不是“刪除”待辦事項列表中元素的正確方法。 @Aravind的答案更好。
但是,如果您真的想使用display:none
,則可以執行以下操作:
https://plnkr.co/edit/eXwAWWeH9N6REsqpzFCq?p=preview
<element ng-style="displayStyle"></element>
<button value="displayNone" ng-click="displayStyle={'display':'none'}">Display none</button>
對Aravinds答案進行細微更改,因為我們需要找到todo
的索引,因此正確的todo
將被刪除
我喜歡在delete中傳遞對象:
(click)="delete(todo)"
需要找到todo
的索引,然后進行splice
。
delete(todo) {
this.todos.splice(this.todos.indexOf(todo),1);
}
剛剛意識到,似乎您只想隱藏待辦事項,而不是完全刪除它。 那么這可以通過以下方式實現。 初始化后,所有待辦事項都可見。 當我們想隱藏它時,可以引入一個新的變量todo。 因此,最初該屬性不存在,因此我們在迭代內部進行標記: *ngIf="!todo.hidden"
,完整的代碼:
<div *ngFor="let todo of todos">
<div class="panel-body" *ngIf="!todo.hidden">{{todo.name}}
<button (click)="hide(todo)" type="button">Hide Todo</button>
</div>
</div>
hide函數將hidden
屬性設置為true:
hide(todo) {
todo.hidden = true;
}
顯然,這並未提供實際取消隱藏待辦事項的選項,但是您的問題中未提及。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.