23

I tried this way:

    @ViewChild('draggable') private draggableElement: ElementRef;

    this.draggableElement.nativeElement.remove();

HTML:

    <div #draggable>Block</div>
raaaay
  • 496
  • 7
  • 14
POV
  • 11,293
  • 34
  • 107
  • 201

4 Answers4

28

Your code can also work, all you have to do is remove element on OnInit(), If you try to remove elements on constructor, the view not be ready.

here's is an example

in .html

    <div #draggable>Block</div>

and in .ts

    export class AppComponent implements OnInit {
      name="Angular";
    
      @ViewChild('draggable') private draggableElement: ElementRef;
    
      constructor() { }
    
      ngOnInit() {
       this.draggableElement.nativeElement.remove();
      }
    }

here's is an Stackblitz demo

raaaay
  • 496
  • 7
  • 14
Aniket Avhad
  • 4,025
  • 2
  • 23
  • 29
3

User Renderer2 service to remove element from dom

removeChild() Implement this callback to remove a child node from the host element's DOM.

@ViewChild('draggable')  draggableElement: ElementRef;
constructor(private renderer2: Renderer2,private el:ElementRef) {}
ngOnInit() {
  this.renderer2.removeChild(this.el.nativeElement,this.draggableElement.nativeElement);
}

Example:https://stackblitz.com/edit/angular-renderer2-remove

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
1

You can use *ngIf right, which will be removed from the DOM when condition fails.

Block
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
  • 3
    I asked another question, not about ngIf – POV Aug 25 '18 at 12:56
  • A little thing against using `*ngIf` but if you're using it, you will not be able to use that element togheter with `@ViewChild()` in the `ngOnInit` since the element isn't existing at that time. – Raphaël Balet Apr 10 '23 at 13:17
-1

If you shall neither not use *ngIf nor nativeElement because what you try to remove is a component I would recommend you to remove the component with pure javascript.

<your-component id="draggable" #draggable>Block</your-component>
document.getElementById('draggable').remove()

If you want to do it in an angular manner, then you would have to use ViewContainerRef. that method is explained in this issue

Raphaël Balet
  • 6,334
  • 6
  • 41
  • 78