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();
}
}
*ngForto render elements, and then modify the array you bind to*ngForand let*ngFordo the adding/removing of DOM elements. Try to avoid direct DOM manipulation in Angular2 and especially try to avoid to do it using jQuery.