Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, moving components via class reference without creating / destroying them

So I'd like to move an angular component and I am well aware I can do it via construction and destruction such as this example: https://stackblitz.com/edit/angular-t3rxb3?file=src%2Fapp%2Fapp.component.html

However I have a scenario that my components are already part of the dom and would like to simple move them around in the dom as is (not create but just move location in dom).

I have a reference to source and destination class locations:

const dom: HTMLElement = this.el.nativeElement;
const elements1 = dom.querySelectorAll('.sourceClass');
const elements2 = dom.querySelectorAll('.destinationClass');

looked online but examples don't seem to have move only and want to avoid jQuery by all means.

and if I was using jQuery I'd use

jQuery('.destination').appendTo('.source');

which works well... Thanks

Sean

like image 568
born2net Avatar asked Aug 11 '26 02:08

born2net


1 Answers

I'm really not sure what exactly you want, but I'd say the Renderer2 would fit your need.

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1> 
  <child1 #child1></child1>
  <div #enmptyBox class="empty-box">
  </div>
  <br>
  <button (click)='moveChild1()'>move comp1 to empty box</button>
  `,
  styles: [`h1 { font-family: Lato; } .empty-box{border: 1px dotted; height: 100px; width: 500px}`]
})
export class HelloComponent {
  @Input() name: string;
  @ViewChild("child1", { read: ElementRef }) child1;
  @ViewChild("enmptyBox", { read: ElementRef }) enmptyBox;

  constructor(private elRef:ElementRef, private renderer: Renderer2) {}

  moveChild1() {
    // first approach 
    this.renderer.appendChild(this.enmptyBox.nativeElement,this.child1.nativeElement);
    // second approach
    this.renderer.appendChild(this.elRef.nativeElement.querySelector('.empty-box'),this.child1.nativeElement);
  }
}

here's a complete stackblitz demo

like image 61
Rachid O Avatar answered Aug 14 '26 14:08

Rachid O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!