Create a duplicate of a div element using renderer 2 and angular framework

Good day! I'm currently facing an issue with viewchild, as it's unable to locate my selector in the HTML code. The objective is to find my 'field' selector in the HTML, clone it, and add a new class to it every time a button is clicked. To achieve this, I intended to utilize renderer 2. Below is my HTML snippet:

<ng-template #effacer4>
  <div *ngIf="Next3"><div #Champ>
  <div class="Champ" [ngClass]="Champ">
      <h1 class="title"> Mortgage(s) to be insured </h1><br>
      
      <h2>Type of mortgage</h2>
        <select class="form-select" aria-label="Default select example">
          <option value="1">Conventional mortgage (amortizable)</option>
          <option value="2">In fine</option>
          <option value="3">Zero Rate Loan</option>
          <option value="4">Bridge loan</option>
        </select> <br>
        <h2>Loan amount</h2>
        <div class="input-group mb-3">
          <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
          <span class="input-group-text">.00 €</span>
        </div>
        <h2>Loan rate</h2>
        <div class="input-group mb-3">
          <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
          <span class="input-group-text">%</span>
        </div>
  
    <h2>Total duration</h2>
        <div class="input-group mb-3">
          <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
          <span class="input-group-text">yr(s)</span>
          <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
          <span class="input-group-text">months</span>
        </div>
        <h2>Including deferred</h2>
        <select class="form-select" aria-label="Default select example">
          <option value="1">1 month</option>
          <option value="2">2 months</option>
          <option value="3">3 months</option>
          <option value="4">4 months</option>
          <option value="5">5 months</option>
          <option value="6">6 months</option>
          <option value="7">7 months</option>
          <option value="8">8 months</option>
          <option value="9">9 months</option>
          <option value="10">10 months</option>
          <option value="11">11 months</option>
          <option value="12">12 months</option>
          <option value="13">13 months</option>
          <option value="14"``">>14 months</option>
          <option value="15">15 months</option>
          <option value="16">16 months</option>
          <option value="17">17 months</option>
          <option value="18">18 months</option>
          <option value="19">19 months</option>
          <option value="20">20 months</option>
          <option value="21">21 months</option>
          <option value="22">22 months</option>
          <option value="23">23 months</option>
          <option value="24">24 months</option>
        </select>
       </div>
      </div></div>
<button (click)="Clone()"class="btn btn-secondary btn-lg"><fa-icon [icon]="faPlusSquare"></fa-icon> Add an insured loan</button>
</ng-template>

And here is the corresponding TypeScript code:

import { Component,ViewChild, ElementRef,Renderer2,AfterViewInit  } from '@angular/core';
import {faFileContract,faChartLine,faCalculator,faBuilding,faHome,faMapMarkedAlt,faChess,faChessKing,faPlusSquare } from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-questionnaire',
  templateUrl: './questionnaire.component.html',
  styleUrls: ['./questionnaire.component.css'],  
})

export class QuestionnaireComponent implements AfterViewInit{
  faFileContract=faFileContract;
  faChartLine=faChartLine;
  faCalculator=faCalculator;
  faBuilding=faBuilding;
  faHome=faHome;
  faMapMarkedAlt=faMapMarkedAlt;
  faChessKing=faChessKing;
  faChess=faChess;
  faPlusSquare=faPlusSquare;
  button: boolean = true;
  SUIVANT:boolean=true;
  Next:boolean=true;
  Next2:boolean=true;
  Next3:boolean=true;
  dynamic=0;
  Champ!: HTMLDivElement;
  
  @ViewChild('Champ')ChampViewChild!: ElementRef;
  
  constructor(private _renderer: Renderer2) {}

  Clone() {
    console.log("Button clicked!");
    this._renderer.addClass(this.ChampViewChild.nativeElement, 'Champ');
    let clonedChamp = this._renderer.createElement(this.ChampViewChild.nativeElement.tagName);
    this._renderer.addClass(clonedChamp, 'Champ');
    this._renderer.appendChild(this.ChampViewChild.nativeElement, clonedChamp);
  }
  
  ngAfterViewInit() {
    if (this.ChampViewChild) {
      this.Clone();
    }
  }
  incrementProgress() {
    this.dynamic += 5;
  };

}

No errors are being displayed in my terminal.

Answer №1

To tackle this issue, I suggest starting by setting up a viewContainerRef to handle the cloning of elements.

You can then proceed to create a view using the TemplateRef with createEmbeddedView and insert it into the viewContainerRef.

<div>
    <ng-container #champContainer></ng-container>
</div>
<ng-template #champ>Your html in here</ng-template>
<button (click)="addDynamicHTML()">Add HTML</button>

Within the component's .ts file, you would have something like:

  @ViewChild('champContainer', {read:ViewContainerRef}) champContainer

  @ViewChild('champ',{read:TemplateRef}) champ

.....

addDynamicHTML(){

  
    //creates a view from the #champ templateRef 

    const view = this.champ.createEmbeddedView()
    //inserts the view created inside the
    this.champContainer.insert(view)
  }

Keep in mind that the createEmbeddedView() method allows for parameters to provide more flexibility in creating new elements (potentially handling the new class for the element). This code snippet serves as a guide on how to approach this development task effectively.

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

What is the method for adjusting the crosshair in highcharts back to its default position?

Working on a project with Angular2, I am currently facing some challenges with my use of highcharts. The issue at hand involves a synchronized chart with one x-axis and multiple y-axes. When hovering over the chart, a crosshair is displayed along with the ...

primeng: Version 16.2.0 of Angular - Get it now!

Upon setting up angular 16.0.0 locally, I used the following command: npx -p @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d5dadfdcc49a8fb2a4beb4beb4">[email protected]</a> ng new Tester --no-stand ...

What is the best way to create a TypeScript function that can return either a string or an object?

I am working with a function that can return either a string or an object. Here is an example: myFunc(path: string): string | object If I already know the exact structure of the object that I am expecting, how can I ensure that the function returns a ty ...

The rule in tslint requires sources imported within a group to be organized in alphabetical order

Currently, I am working with a setup that involves create-react-app in combination with custom-react-scripts-ts. Below is the code snippet for my component: import * as React from "react"; import "./App.css"; // reset.css import ErrorsContainer from "./ ...

A versatile method for transforming enums into arrays that can handle null values

Looking for a simpler way to create a TypeScript function that converts an enum to an array, including support for null values. Here's an example of what I'm trying to achieve: enum Color { RED = "Red", GREEN = "Green&qu ...

Enhance your MaterialUI Button with a higher order component that accepts a component

I am currently working on implementing a Higher Order Component (HOC) for the MaterialUI Button component: import {Button as MUIButton, ButtonProps} from '@material-ui/core'; import * as React from 'react'; export const Button = (props ...

Is it possible to utilize varying parameter types within a function in JavaScript?

With the limitation of not being able to overload functions in JS, my attempt to pass different types has failed: static fromRaw(raw: CourseRaw | CourseNameSearchRaw): Course | CourseNameSearch { if (raw instanceof CourseRaw) { return { ...

Encountering issues when verifying the ID of Angular route parameters due to potential null or undefined strings

Imagine going to a component at the URL localhost:4200/myComponent/id. The ID, no matter what it is, will show up as a string in the component view. The following code snippet retrieves the ID parameter from the previous component ([routerLink]="['/m ...

Locating a specific entry in a custom object array based on a property

Currently working on an Angular 2 app using Typescript and encountering a challenge. There is a service that retrieves an array of questions structured like this: export class Question { constructor(public id: number, public quest ...

Mastering Bootstrap 4 flexbox for optimal content filling: A comprehensive guide

I am currently working on an angular app integrated with bootstrap 4. The challenge I am facing is related to the layout design. I have a fixed navbar at the top and a content area below it. Within the content area, I have a div that includes header and fo ...

React typescript is handling various promise response types, causing strange behavior in type-checking

I recently started utilizing the and I seem to be encountering a perplexing issue. If further context is needed, please let me know and I will provide it. All the necessary functions and types are mentioned below my explanatory paragraphs. Your assistance ...

"Unlock the power of remote-redux-devtools in NgRx: A step-by-step guide

Currently, I am utilizing NgRx in an Angular NativeScript project for Android and iOS apps, and it is proving to be quite effective. However, one aspect that concerns me is the inability to use @ngrx/store-devtools and the Redux DevTools Chrome extension d ...

Incorporating FormControl Validators within a Child Component in Angular

Having two Angular Components, one is called parent.ts and the other is named child.ts. Parent.ts contains a Form group, while child.ts passes the Form data via CVA to the parent. Now, I am looking to create a reusable child component that can generate c ...

Ways to prevent encountering the "ERROR: Spec method lacks expectations" message despite achieving success

My Angular HTTP service is responsible for making various HTTP calls. Below is a snippet of the service implementation: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() expor ...

I am facing an issue with Angular's ngFor where it is not displaying the data fetched from my Spring Boot application on the browser

While I was working on establishing connectivity between SpringBoot and Angular, I encountered an issue where the data fetched using getmapping in Spring would successfully print on the server side. However, when passing this data to Angular through a serv ...

Ensure that every member of an object adheres to a particular generic interface in some capacity

Can a TypeScript index signature type be used to enforce that every index adheres to a generic interface? I want to define code like this: interface HasState<T> { state : T; } interface ModuleDefinition { [moduleName : string] : <T>HasSta ...

Styling the checked state of a switch in NativeScript/Angular with ngModel/FormBuilder

Let's explore the styling of a switch element within Angular: <Switch class="switch" formControlName="answer"></Switch> One approach involves targeting the switch with checked attribute, setting its background-color and text color accord ...

What is the best way to specify a React component that has been initialized in a Typescript interface?

As a newcomer to both React JS and Typescript, I am facing an issue with a function that expects an object by interface: interface ModalContents { component: React.Component, ... } export default function buildModal(contents : ModalContents){ ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

The validation status of Angular's custom form array remains in a PENDING state when utilizing asynchronous validators

I've created a custom asynchronous postal code validator that can be used with Template Driven forms. @Directive({ selector: '[appAsyncPostalCode]', providers: [ { provide: NG_ASYNC_VALIDATORS, useExisting: AsyncPostalCodeValidatorDi ...