Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How delete element.nativeElement from DOM?

I tried this way:

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

    this.draggableElement.nativeElement.remove();

HTML:

    <div #draggable>Block</div>
like image 823
OPV Avatar asked Aug 25 '18 12:08

OPV


3 Answers

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

like image 174
Aniket Avhad Avatar answered Sep 19 '22 15:09

Aniket Avhad


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

like image 41
Chellappan வ Avatar answered Sep 19 '22 15:09

Chellappan வ


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

Block
like image 43
Suresh Kumar Ariya Avatar answered Sep 18 '22 15:09

Suresh Kumar Ariya