I am currently struggling with adding an HTML form to my Angular project

Currently utilizing Angular framework

  • My Add button triggers the appending of HTML content upon multiple clicks.
  • The issue arises when I click the Add button, as the appended content fails to display textboxes or dropdowns. Instead, only the field names appear as plain text.

I would like to share my code snippet below:

TS

export class AppComponent  {
  name = 'Angular';
  htmlToAdd : any ;
  newHtml : any 
  constructor(private elementRef:ElementRef) {}
  add(){
     this.htmlToAdd = `  <form action="/action_page.php">
                  First name:<br>
                  <input type="text" name="firstname" value="Mickey">
                  <br>
                   Last name:<br>
                  <input type="text" name="lastname" value="Mouse">
                  <br><br>
                  <input type="submit" value="Submit">
                  </form> `
      }
}

HTML

<div class="one" [innerHtml]="htmlToAdd"></div> 
<button (click)='add()'> Add </button>
<div [innerHtml]='newHtml'></div>

Answer №1

It would be much more efficient to use ngFor in this scenario.

Code Snippet for HTML

<form>
    <ng-container *ngFor="let item of items">
        <input type="text" name="firstname" value="John">
         <input type="text" name="lastname" value="Doe">
    </ng-container>
    <input type="submit" value="Submit">
</form>

<button (click)="addItem()"></button>

Consider implementing something similar to the following TypeScript code to better manage your data.

TypeScript Code

items: any[] = [];

addItem() {    
    this.items.push(this.items.length + 1)
}

Answer №2

Issue: The variable htmlToAdd is not being appended as expected. It keeps getting re-initialized every time the add() method is called.

To resolve this problem, consider making the following change:

Typescript Solution

import { Component, ElementRef } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";
  htmlToAdd = '';

  constructor(private elementRef: ElementRef) {}

  add() {
    this.htmlToAdd = `${this.htmlToAdd}<form action="/action_page.php">
      First name:<br>
      <input type="text" name="firstname" value="Mickey">
      <br>
      Last name:<br>
      <input type="text" name="lastname" value="Mouse">
      <br><br>
      <input type="submit" value="Submit">
    </form> `;
  }
}

HTML Code

<div class="one" [innerHtml]="htmlToAdd"></div> 
<button (click)='add()'> Add </button>

Check out the Stackblitz example for a live demonstration: https://stackblitz.com/edit/angular-dpm4px

I hope this solution resolves your issue!

Note: It's important to implement dynamic field configuration correctly.

For a better approach, consider using form arrays in reactive forms. Learn more about angular forms and operations here: https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays

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

Enhancing the aesthetic appeal of Angular2 Google Maps

Hey there, I'm a newcomer to Angular2/Typescript and I've been working on styling a map in my Angular2 project. I integrated a map using the Angular2 Google Maps Components, but I'm having trouble with applying styles through the undocumente ...

Explore lengthy content within Angular 2 programming

I have a lengthy document consisting of 40000 words that I want to showcase in a visually appealing way, similar to HTML. I aim to include headers, paragraphs, and bold formatting for better readability. Currently, I am developing an Angular application. D ...

Steps to address the error "zone is not defined" in your project

After updating a project from Node.js 6 to Node.js 10 and making various changes and version upgrades, I encountered failing test cases. No matter what fixes I attempted, the tests continued to fail with the error message "ReferenceError: Zone is not defin ...

"This error message states that the use of an import statement outside a module is not allowed

After searching for a solution without any luck, I decided to start a new discussion on this topic. Currently, I am working on azure functions using Typescript and encountering the following error: import { Entity, BaseEntity, PrimaryColumn, Column, Many ...

Steps for retrieving multiple documents from Firestore within a cloud function

In my cloud function, I have set up a trigger that activates on document write. This function is designed to check multiple documents based on the trigger and execute if/else statements accordingly. I have developed a method that retrieves all documents u ...

What's the best way to alter an HTTP request response and conveniently retrieve it before sending it back from an Observable?

I am in the process of upgrading to Angular version 5. Previously, I was using @angular/http, but now I need to switch to @angular/common/http and utilize HttpClient. My current setup involves making HTTP requests in services, which makes them easy to reu ...

Executing a function after Angular 2 Component is initialized

I am facing an issue. I am looking for a global service and I came across this helpful resource: Link. Although it works, I am now interested in having an event triggered after my component has been initialized and bootstrapped. Does anyone know of such a ...

Encountering an issue with Angular virtual scrolling: ViewDestroyedError arises when trying to utilize a destroyed view during detectChanges operation

My implementation involves using virtual scrolling from the cdk within a trigger-opening sidenav on a mat-radio element. Here is the code snippet: ts - ... @Component({ selector: 'app-generic-options-list', templateUrl: './generic-opt ...

navigating through different pages on a react-native application

While building my app in react-native, I encountered some issues with setting up the navigation. I referred to the react-native documentation for guidance, specifically this navigation guide. The guide mentioned passing an object named "navigation" to your ...

tips for accessing the value outside of the subscription in angular2

Created a function within the component.ts file inside the constructor: constructor(private _visitService: VisitService,) { this._visitService.getchartData().subscribe(data => { this.fetchedData = data console.log("INSIDE SUBS ...

leveraging lite server with actual data

Working with Lite server and Browser-sync has been a great experience for quick UI programming. However, I've encountered an issue when attempting ajax calls to retrieve data from my actual web server. It seems like a fundamental task to fetch json o ...

Leverage the globalDependencies feature in Angular2 to utilize Typescript tsd files

I am attempting to incorporate typescript tsd's from DefinitelyTyped into an Angular2 project (RC.0), but encountering issues with loading global dependencies properly: typings install --save dt~hellojs --global --save npm install --save hellojs Her ...

What is the best way to set up a FormGroup when the FormControlName is dynamic and subject to change?

Hello, I am new to Angular and encountering a particular scenario. On my HTML page, there is a form (formgroup) with a div inside it that uses the ngFor directive to iterate through an object as needed. Let's say there is an input field with formCon ...

Determining the output type by considering the presence of optional parameters

function customFunction<T>(defaultValue?: T) { return defaultValue; } const definitelyNullOrUndefined = customFunction<string>(); // type: string | undefined const definitelyStringType = customFunction<string>('foobar'); // ...

The routing functionality in an Angular Element seems to be malfunctioning when used in a separate Angular project. Instead of displaying the expected routes, only the "<router-outlet></router-outlet>" tags are visible on the website

The current situation: Our team is facing the challenge of integrating multiple angular frontend micro-services into a single application. To achieve this, we have chosen to use the Angular-Elements approach which resulted in a large JS-file when exportin ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

Error: The @use directive must come before any other rules in Angular

Error message: Issue: Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): Error Details: HookWebpackError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js) ...

Having trouble fixing TypeScript bugs in Visual Studio Code

I am encountering a similar issue as discussed in this solution: Unable to debug Typescript in VSCode Regrettably, the suggested solution does not seem to resolve my problem. Any assistance would be greatly appreciated. My directory structure looks like ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

During the build process, NextJS encountered an issue locating the constants.js module

I encountered an error while executing next build using next version ^10.2.3. I attempted to remove the node_modules and .next folders, then reinstalled dependencies with npm install && next build, but the issue persists. Error: Cannot find mod ...