.remove () in Angular 2

Suppose I have a list of 5 items, and I want the user to be able to remove the desired entry from the list. In this case, if I use jQuery, I can specify a specific delete button class and use 'this' to indicate its closest parent, and then use '.remove ()' to remove it from the DOM. Example:

$('.delete').click(function(){
  $(this).closest('li').remove();
})  
ul li {
padding:0.5em;
list-style-type:none;
margin-bottom:0.5em;
}

ul li span a {
margin-left:100px
}

ul li span a:hover {
text-decoration:underline;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
      <li>Item 1<span class="delete"><a>Delete</a></span></li>
<li>Item 2<span class="delete"><a>Delete</a></span></li>
<li>Item 3<span class="delete"><a>Delete</a></span></li>
<li>Item 4<span class="delete"><a>Delete</a></span></li>
<li>Item 5<span class="delete"><a>Delete</a></span></li>
    </ul>
Run codeHide result

I want me to have the same functionality in Angular 2?

Real scenario code:

    @Component({
  selector: 'myLevels',
  template: `
      <template #clone>
        <div class="addedLevel">
        <p>Paragraph Two</p>
        <span #element><i class="fa fa-trash deleteLevel" (click)="removeLevel()"></i></span>
        </div>
      </template>
      <div #container></div>

      <button (click)="cloneTemplate()">Clone Template</button>
  `,
})

export class level implements OnInit, AfterViewInit {

  // What to clone
  @ViewChild('clone') template: any;

  // Where to insert the cloned content
  @ViewChild('container', { read: ViewContainerRef }) container: any;

  cloneTemplate() {
    this.container.createEmbeddedView(this.template);
  }

  constructor(private element: ElementRef) { }
  ngOnInit() { }
  ngAfterViewInit() {
    // $(document).on('click', '.deleteLevel', function() {
    //   $(this.closest('.addedLevel')).remove();
    // })
  }

  removeLevel() {
    debugger;
    console.log(this.element);
    this.element.nativeElement.querySelector('.addedLevel').remove();
  }

}
+4
source share
2 answers
+1

html

 <form #newForm="ngForm" novalidate (ngSubmit)="savenew(newForm)">
 <ul>
 <li *ngFor="let item of items; let index = index">
  <div class="form-group">
    <input type="text" id="name{{index}}" class="form-control" 
     name="name{{index}}" ngModel #name{{index}}="ngModel" value=
   {{item.name}}>
    <input type="text" id="age{{index}}" class="form-control" 
   name="age{{index}}" ngModel #age{{index}}="ngModel" value={{item.age}}>
    <button type="Button" (click)="remove(index)" >Remove</button>
  </div>
 </li>
</ul>
<button type="button" (click)="addb()">Add</button>
<button type="submit">Submit</button>
</form>

TS

 items: any[] = [
 { name: '', age :'' }
 ];
 addb(){
  this.items.push({name:'',age:''});
 }
 remove(index: number): void {
  this.items.splice(index, 1);
 }

@sunit ,

0

Source: https://habr.com/ru/post/1673094/


All Articles