Angular, manipulating components through class references instead of creating or destroying them

I am exploring ways to move an angular component, and I understand that it can be achieved through construction and destruction. For example, you can refer to this link: https://stackblitz.com/edit/angular-t3rxb3?file=src%2Fapp%2Fapp.component.html

However, I am facing a scenario where the components are already present in the DOM, and I simply want to relocate them within the DOM without creating new ones.

I have references to both source and destination class locations:

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

I have searched online but couldn't find any examples of moving elements directly without creating new ones. Additionally, I prefer not to use jQuery for this purpose.

If I were using jQuery, I would typically do something like:

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

This approach usually works well. Thanks!

Sean

Answer №1

If you're uncertain about the requirements, consider utilizing the Renderer2 for your task.

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

Check out the full demonstration on StackBlitz here

Answer №2

Thank you for the assistance. After conducting some tests, I found that using a class is not feasible because the proper nativeElement cannot be obtained. ViewChild elementRef poses a problem as my components are generated dynamically. I have decided to approach it differently. Instead of navigating through the DOM, I am maintaining its own elementRef in the component I wish to reference:

    @ViewChild('tableList', {read: ElementRef}) tableListsComp;

    constructor() {
    }

    ngAfterViewInit() {
        if (this.field.inputType === 'tablelist') {
            this.elementRefs = this.tableListsComp;
        }
    }

Later on, I retrieve it using this.elementRefs with the help of a service to which the component is linked.

Once I have the instance, I can perform the following actions:

const compRef1 = this.getFormComponentViaServiceRef('Page');
this.render.appendChild(this.tab1.nativeElement, compRef1.componentRef.instance.elementRefs.nativeElement);

Appreciate the guidance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing "timeout while waiting for third-party check iframe message" when using Keycloak and Angular

I'm in the process of securing an Angular application with a Keycloak server. I've followed several tutorials with similar instructions, but I encountered an issue that has me stuck: Timeout when waiting for 3rd party check iframe message. My ...

Is it possible to utilize instanceof to verify whether a certain variable is of a class constructor type in TypeScript?

I am currently facing an issue with a function that takes a constructor as a parameter and creates an instance based on that constructor. When attempting to check the type of the constructor, I encountered an error. Below are some snippets of code that I ...

I seem to be stuck in an endless cycle with React hooks and I can't figure out the root cause

Explore the example here: https://codesandbox.io/s/wandering-wildflower-764w4 Essentially, my goal is to achieve the following: In the provided example, I have a server validation function that has been mocked. My objective is to maintain the state local ...

Using Bootstrap 4 Datatablejs within an Angular4 CLI project

Just finished developing a web application using Angular 4 and Angular CLI tool. Currently, I am trying to display a table with DataTableJs on one of the pages of my app. However, the styling is not coming out as expected. https://i.stack.imgur.com/H5IIT ...

Transform a string into title case and eliminate any special characters in Angular 6

I've written some code that displays text in title case using a pipe. {{person.name| titlecase}} Now, I want to create another filter or pipe that will remove special characters from the string and only keep numbers and letters. For example: "john ...

Encountering an Issue with Angular 9's HttpInterceptor: Unraveling the Mystery of

For my Angular 9 application, I have implemented an HttpInterceptor as shown below: export class AppHttpInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { ...

Steps to resolve the issue of "npm WARN deprecated [email protected] : request has been deprecated, see https://github.com/request/request/issues/3142" error on Windows 10

Seeking assistance with setting up Angular 4 on my Windows 10 system. Upon running node -v and npm -v, the version is displayed without any issues. However, when attempting to execute npm install -g @angular/cli, I encounter the following error message: np ...

What is the process for displaying the attributes of a custom object in Typescript?

I need help returning an array of prop: value pairs for a custom object using the myObject[stringProp] syntax. However, I keep encountering this error message: TS7053: Element implicitly has an 'any' type because expression of type 'str ...

Error in Angular 12: Unable to access 'bootstrap' property from null

During the upgrade process of my Angular 10 application to Angular 12, I encountered an error that says: TypeError: Cannot read property 'bootstrap' of null Below are the files related to my Angular setup: tsconfig.json { "compileOnSave& ...

I prefer the value to switch to false whenever I navigate to a new route and then return to the previous route, as the sidebar remains open

click here for image details view image description here Struggling to set the value as false when revisiting this site. Need assistance! Could someone lend a hand, please? ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Acquire information from an Angular service and output it to the console

I am having trouble logging data from my service file in the app.component file. It keeps showing up as undefined. Below is the code snippet: service.ts getBillingCycles() { return this.http.get('../../assets/download_1.json'); }; app.com ...

Exploring Angular Material's Autocomplete feature and staying updated with incoming data changes

https://material.angular.io/components/autocomplete/examples export class AutocompleteAutoActiveFirstOptionExample implements OnInit { myControl = new FormControl(); options: string[] = ['One', 'Two', 'Three']; filtered ...

Utilizing React with Typescript: A guide to working with Context

I have a super easy app snippet like import React, { createContext } from 'react'; import { render } from 'react-dom'; import './style.css'; interface IAppContext { name: string; age: number; country: string; } const A ...

Choosing Vue select options depending on a condition

I am working on a dropdown template with Vue.js and have encountered some challenges. Here is the basic structure of my dropdown: <select v-model="selectedClient" class="stat-select text-u-c"> <option disabled value="">Please select a Client ...

Encountering issues with Google authentication functionality while using AngularFire2

Currently in the process of setting up Google Authentication with Firebase and AngularFire2. The setup seems to be partially functional, however, there are some unusual behaviors that I am encountering. Upon the initial loading of the app, the Login button ...

Basic Karma setup with Typescript - Error: x is undefined

I am trying to configure a basic test runner using Karma in order to test a TypeScript class. However, when I attempt to run the tests with karma start, I encounter an error stating that ReferenceError: Calculator is not defined. It seems like either the ...

Creating instance methods in a TypeScript object can be accomplished by defining the methods within the object's class definition. When the object is

As a seasoned Java developer, I've recently been dabbling in TypeScript. Let me introduce you to my user object: export class User { id: string; name: string; email?: string; unit: string; street: string; postalcode: string; ...

Styling of Bootstrap HTML element not appearing as expected

Recently, I've been trying out a new approach by embedding Bootstrap components in an iframe. However, despite loading the necessary stylesheet and scripts, the elements seem to be missing their styles. Can anyone shed some light on why this might be ...

Angular Material: Enhanced search input with a universal clear button

After searching for a cross-browser search control with a clear button similar to HTML5, I found the solution rendered by Chrome: <input type="search> The code that gave me the most relevant results can be found here. I used the standard sample w ...