Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.remove() function in Angular 2

Tags:

angular

Suppose, I have a list of 5 items and I want the user to be able to delete his desired entry from the list. In this case, if I use jQuery, I can point to the particular delete button class and use 'this' to point 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>

I would like to whether I can have the same functionality in Angular 2?

Real Scenario code is:

    @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();
  }

}
like image 933
Sunit S Avatar asked Nov 08 '22 00:11

Sunit S


1 Answers

As the others have pointed out, there's absolutely no need to even access the DOM yourself. Angular takes care of that for you. Just bind to an array in your component using ngFor and mutate that array using a method on your component.

See here for a quick example: https://plnkr.co/edit/bGlsxog3tx13aszBv84u?p=preview

like image 164
Brother Woodrow Avatar answered Nov 15 '22 07:11

Brother Woodrow