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

Leverage the TypeScript compiler's output from a .NET library within a Blazor application by referencing it

I am currently facing an issue with three different levels: Main Issue: I have developed a Blazor WebAssembly (WASM) application that requires JavaScript, but I prefer to use TypeScript. To address this, I have added a tsconfig file and the TypeScript cod ...

How can I display a header from one page on a different page in Ionic?

Using Ionic 3 on my Home Page, I have the following code snippet. Whenever the searchMore button is clicked, it leads to a new page. The objective is to display "Cook With What is in My Pantry" from the h5 tag on the new page. <ion-grid> <io ...

The attribute 'title' is not found in the data type 'Projects[]'

When attempting to retrieve data from a specific link, I encounter error TS2339: Property 'title' does not exist on type 'Projects[]', despite the presence of the 'title' property in 'Projects'. The goal is to access ...

The NextJS image URL remains constant across various endpoints

Currently experiencing an issue with my Channel Tab where the icon and name of the channel are displayed. The problem is that every time I switch channels, the icon remains the same as the first channel I clicked on. PREVIEW This is the code I am current ...

Troubleshooting the "TypeError: Swiper.initialize is not a function" Issue in React Swiper using TypeScript

Struggling to implement Swiper in a project using nextJs and Typescript. Attempting to modify styles with injectStyle but encountering an error during initialization without knowing how to resolve it. import { useRef, useEffect } from "react"; im ...

Is there a way to simulate the BeforeInstallPromptEvent for testing in Jasmine/Angular?

I'm currently working on testing a dialog component that manages the PWA install event triggered manually when a specific function is invoked. The goal is to handle the promise returned by the BeforeInstallPromptEvent.userChoice property. However, wh ...

Deliver output data from Spring to Angular

I am working on a microservice in Spring that needs to return a value distinguishing between users and admins to Angular. So far, I have managed to return a boolean value, but I am struggling to change it to work with strings or any other data type. I trie ...

Combining two elements in Angular 2

I am looking to find the intersection of two objects. My goal is to compare these objects and if they have matching values on corresponding keys, then I want to add them to a new object. obj1 = { "Projects": [ "test" ], "Companies": [ "facebook", "google ...

What is the reason behind CORS errors being triggered by the inclusion of an HTTP Interceptor?

I am currently building an Angular 6 application that communicates with a PHP REST Api. I am running my development environment on localhost, and in order to avoid CORS errors, I had to enable the Access-Control-Allow-Origin: * setting. Lately, I have bee ...

Linking to a variable that could potentially be non-existent

How can I properly bind to myVariable even if it may not be present? (myVariable comes from a service that may not always be active) <input pInputText type="text" [size]="size" [value]="myVariable" style="cursor: poin ...

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

Protecting Your Angular Application with the Angular App Shell Architecture

I have a significant project that utilizes Angular's App Shell Model combined with Angular MSAL.js (v2). One issue I am encountering is ensuring that the guard checks are invoked before the app shell is built, rather than just for the projects injecte ...

Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this: <div *ngFor="let person of persons"> {{person.name}} {{person.surname}} <but ...

Is the latest Swiper JS version compatible with outdated web browsers?

Seeking information on browser compatibility. I am interested in upgrading to the latest version 8.4.5 of Swiper JS for my project, currently using version 4.1.6. Upon examining their shared Github repository file .browserslistrc, I noticed changes that ta ...

Angular Table Expansion Panel: Expanding Your Data in Style

Recently started exploring Angular and struggling to find a straightforward method to incorporate a table with an expansion slider containing dropdown menus. You can view the wireframe design Gif I created using Javascript by visiting this link: I came a ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

Utilizing nested endpoints in Angular resource with a Node.js server

In my Angular application, I have a resource called /cars with the endpoint defined as $resource('/cars/:carsId'); This allows me to retrieve all cars or a specific car. On the server side, I've implemented middleware to ensure that carsI ...

How can I ensure that reactive form fields are properly validated in Angular2?

I am currently facing issues with validating Reactive form field in Angular 2. I have implemented a custom validator for this purpose, but it seems like my approach is not yielding accurate results as some of the test cases are failing. If anyone has insig ...

Strategies for effectively searching and filtering nested arrays

I'm facing a challenge with filtering an array of objects based on a nested property and a search term. Here is a sample array: let items = [ { category: 15, label: "Components", value: "a614741f-7d4b-4b33-91b7-89a0ef96a0 ...

The stack property of [object Object] cannot be updated, as it only has a getter method

I can't figure out why I'm receiving this specific error in the Plunker below. Cannot set property stack of [object Object] which has only a getter Access the Plunker here: https://plnkr.co/edit/IP1ssat2Gpu1Cra495u2?p=preview The code causi ...