Creating multiple copies of a form div in Angular using Typescript

I'm attempting to replicate a form using Angular, but I keep getting the error message "Object is possibly 'null'". HTML:

<div class="form-container">
      <form class="example">
        <mat-form-field>
          <mat-label>Name</mat-label>
          <input type="text" matInput [formControl]="emailFormControl" [errorStateMatcher]="matcher"
                 >
          <mat-error *ngIf="nameFormControl.hasError('name') && !nameFormControl.hasError('required')">
            Please enter a valid name
          </mat-error>
          <mat-error *ngIf="nameFormControl.hasError('required')">
            Please enter name
          </mat-error>
        </mat-form-field>
          <button mat-icon-button color="primary" class="delete" matTooltip="Remove item">
            <mat-icon>delete</mat-icon>
          </button>
      </form>
      <button id="addEmailField" (click)="clone()">
        <mat-icon>add</mat-icon> Add new item
      </button>
    </div>

TS:

 clone() {
const example = document.querySelector('.example');
const clone = example.cloneNode(true);
document.querySelector('.form-container').appendChild(clone);

}

I am looking for way to duplicate the form container. Any alternative solutions would be greatly appreciated.

Answer №1

To ensure safety, you can utilize the null check operator (represented by the ? before the dot) - this essentially checks for existence. For example, a?.doSomething() will be interpreted as if(a){a.doSomething()}.

const element = document.querySelector('.element');
const duplicate = element?.cloneNode(true);
document.querySelector('.container')?.appendChild(duplicate);

Alternatively, you can take a more detailed approach:

const element = document.querySelector('.element');
if(element) {
   const duplicate = element.cloneNode(true);
  const container = document.querySelector('.container');
  if(container){
    container.appendChild(duplicate);
  }
}

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

Observing changes in a parent component variable with Angular

One feature of my form is that it consists of a parent component and a child component. To disable a button within the form, I utilize a function called isDatasetFilesValid() which checks a specific variable (datasetList[i].fileValid). This variable is mo ...

"I am experiencing an issue with the PrimeNG year picker as it is unable

My goal was to set up a simple PrimeNG calendar with just a year picker. I followed the implementation instructions from the documentation: <p-calendar inputId="year" [(ngModel)]="date1" view="year" dateFormat=" ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

The documentation for Angular guards is riddled with vague and obfuscating statements

I've been delving deep into Angular lately, and I found the documentation to be quite enlightening. currently, I'm focused on learning about guards. In my research, I came across this intriguing statement: The router evaluates CanDeactiva ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Change the color of the Parent Menu when a childMenu is clicked on using CSS and HTML

<li class="btn-group" mdbDropdown> <a mdbDropdownToggle id="ParentId"> <i class="nav-item"></i> MainMenu <i class="fa fa-angle-down"></i> </a> <div class=" ...

Creating a TypeScript library with Webpack without bundling may seem like a daunting task, but

Currently, I am developing a React component package using Typescript and NPM. During my research, I discovered that generating individual .js and .d.ts files is more beneficial than bundling them into one bundle.js file. However, I am facing difficulty in ...

Employing a provider within a different provider and reciprocally intertwining their functions

I'm currently facing an issue with two providers, which I have injected through the constructor. Here's the code for my user-data.ts file: @Injectable() export class UserDataProvider { constructor(private apiService: ApiServiceProvider) { ...

Creating a consistent template for typing TypeScript generics

Is it possible to modify a generic function so that it can accept an unlimited number of arguments and concatenate them with .'s? This function should be able to handle nested objects with any number of keys. The current code snippet works when manua ...

When I receive a 404 response from the API, I aim to start my observable

How can I trigger my observable initialization when receiving a 404 response from the API? The code snippet below is not working as expected. const urlParams = { email: this.email }; this.voicesProfileObservable$ = this.service.request<any>( AVAI ...

The issue TS2305 arises when trying to access the member 'getRepositoryToken' from the module "@nestjs/typeorm" which is not exported

Recently, I've been exploring the world of Nestjs and TypeOrm packages, but I've stumbled upon a series of TS errors that have left me perplexed. While I've managed to resolve many of them, there's one persistent error that continues t ...

Unusual Type Inference in Typescript {} when Evaluating Null or Undefined

Upon upgrading from typescript 4.9.3 to 5.0.2, we encountered an error when asserting types. Can someone explain why the function "wontWorking" is not functioning correctly? I expected this function to infer v as Record<string, any>, but instead it ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

Creating a JSX syntax for a simulated component and ensuring it is fully typed with TypeScript

Looking for some innovative ideas on how to approach this challenge. I have a test helper utils with added types: import { jest } from '@jest/globals' import React from 'react' // https://learn.reactnativeschool.com/courses/781007/lect ...

Utilizing TypeScript's conditional return type with an object as a parameter, and incorporating default values

Is it possible to create a function where the return type is determined by a string, with some additional complexities involved? I'm looking to achieve the following: The parameter is contained within an object The parameter is optional The object it ...

TypeORM's one-to-many relationship alters the primary entity once the relationship has been established

When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend entity with a specific user, the target field of ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: Query How can I enable real-time inspections to occur immediately? (I've already attempted invali ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...