简体   繁体   中英

How to make the element `display: none` by clicking the button

I want to implement a function to hide elements when button is clicked in an application built using 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>

I want to know how to make the todo disappear when the button is clicked with the above code. Although it is an elementary question, please teach.

You should be removing that todo item as below

delete(id:number){
    this.todos.splice(id,1)
}

I think this is not the right way to 'remove' an element on a todo list. @Aravind answer is better for it.

But if you really want to use display:none , you can do this like :

https://plnkr.co/edit/eXwAWWeH9N6REsqpzFCq?p=preview

<element ng-style="displayStyle"></element>
<button value="displayNone" ng-click="displayStyle={'display':'none'}">Display none</button>

Small changes to Aravinds answer, since we need to find the index of the todo , so that right todo will be deleted

I like to pass the object in delete:

(click)="delete(todo)"

Need to find the index of the todo and then splice .

delete(todo) {
  this.todos.splice(this.todos.indexOf(todo),1);
}

Update:

Just realized that it seems that you only want to hide the todo, and not delete it entirely. Well this can be achieved with the following. Upon initialization all todo's are visible. We could introduce a new variable to todo, when we want to hide it. So initially this property doesn't exist, so we mark inside the iteration: *ngIf="!todo.hidden" , complete code:

<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>

And the hide function sets the hidden property as true:

hide(todo) {
  todo.hidden = true;
}

This doesn't obviously give the option to actually unhide the todo, but that was not mentioned in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM