5

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

}
10
  • Yes you can. Try *ngFor for repeatation of items and (delete) event binder and emitter. Refer Angular 2 documents. Commented Mar 24, 2017 at 9:18
  • Ok, the real scenario is that I have one HTML template, which I am cloning and appending to a parent div using selector. This is having a delete icon too in it. Now, I want to have the same functionality as above on this. Please note that I am not using *ngFor in this case. Cloning the template and appending on a button click. Commented Mar 24, 2017 at 9:21
  • 2
    Real scenario code? Commented Mar 24, 2017 at 9:24
  • Hi Amit, I have edited the question to show you the real code, you can check it there. I am sorry if the code looks a bit messy as it is still an app under development. As you can see, I have resorted to jQuery as of now, so looking for an Angular solution. Commented Mar 24, 2017 at 9:30
  • 2
    You should use *ngFor to render elements, and then modify the array you bind to *ngFor and let *ngFor do the adding/removing of DOM elements. Try to avoid direct DOM manipulation in Angular2 and especially try to avoid to do it using jQuery. Commented Mar 24, 2017 at 9:37

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

The example is a good one, however, the issue remains the same, I am not concerned about generating 'li' elements from array using *ngFor. My issue is that after appending HTML elements and tags from the cloned templates, how do I delete the particular 'div' where the click happened.
You can pass $event as a parameter to the click function, which will send the raw event data. Then, I suppose, get the srcElement property of that. That gives you the element that fired the click event and you can work from there.
0

html file

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

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

@sunit Hope this what u expected

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.