Issues arise when dynamically generated <input> elements are not displaying on the webpage

I am facing an issue with rendering a form dynamically using a string in my Angular application.

Upon clicking the "Add Step" button, the template string is supposed to be added to a list and displayed using ngFor directive. However, I am only seeing the <h3> tag on the screen instead of the input field.

Here is what happens before the button click:

https://i.sstatic.net/FctPg.png

And here is how it looks after - the input field does not show up either on the screen or in the HTML:

https://i.sstatic.net/yjgKd.png

This is how the TypeScript code looks like:

scenarioTemplate = `
  <div id="content">
    <h3>Name</h3>
    <input name="{{i}}" [ngModel]="i">
  </div>`;

steps = [];

addScenarioStep() {
    this.steps.push(this.scenarioTemplate);
}

And here is the corresponding HTML code snippet:

<form #myForm="ngForm">
  <fieldset ngModelGroup="inputs" #inputs="ngModelGroup">
    <ng-container *ngFor="let step of steps; let i = index">
      <div [innerHTML]=step attr.stepId="{{i}}"></div>
    </ng-container>
  </fieldset>
</form>
<button id="addStepBtn" type="button" class="btn btn-light" (click)="addScenarioStep()">Add Scenario Step +</button>

Answer №1

  1. Insert the entire content
  <div id="content">
    <h3>Name</h3>
    <input name="{{i}}" [ngModel]="i">
  </div>

into the template, rather than the TypeScript file.

  1. Avoid changing the array directly. Instead of
this.steps.push(newElem);

use

this.steps = [...this.steps, newElem];

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 sending a file array together with other string/int variables from JavaScript to PHP

I am looking to pass the imageArray[] along with a variable trackNo. Passing the imageArray[] is not an issue, but I am unsure of how to include other variables with the FormData(). When researching online, I only came across examples of people passing a ...

What are the steps to update the title and creator details in the package.json file of an Openshift Node.js application?

Recently delving into the world of node.js and PaaS platforms like Openshift, I find myself faced with a perplexing issue. How exactly can I modify the values generated by Openshift in the package.json file without encountering any errors? Each time I at ...

How can I omit extra fields when using express-validator?

Currently, I am integrating express-validator into my express application and facing an issue with preventing extra fields from being included in POST requests. The main reason for this restriction is that I pass the value of req.body to my ORM for databas ...

Mapped types: Specify mandatory properties depending on whether an array of identical objects includes a specific string value

Can an object property be set to required or optional based on the presence of a specific string in an array within the same object? type Operator = "A" | "B" type SomeStruct = { operators: Operator[]; someProp: string; // this should be ...

How can I implement internal redirection within a ReactJS application?

As someone who is new to React, I've been exploring how to internally redirect pages in ReactJS. Specifically, I have two pages named "register" and "register2". In the register page, the process involves checking if an email exists in the database. I ...

Conditionals in Angular 2 using Sass

Looking to apply this style with Sass or CSS: IF :host.form-control MATCHES .ng-valid[required] OR .ng-valid.required THEN :host ::ng-deep input.form-control = border-left: 5px solid #42A948; Appreciate the help! ...

Initial 16 characters of the deciphered message are nonsensical

In a specific scenario, I encounter data encryption from the API followed by decryption in TypeScript. I have utilized CryptoJS for decryption in TypeScript. Below is the decryption code snippet: decrypt(source: string, iv: string): string { var key = envi ...

Angular example of Typeahead feature is sending a blank parameter to the backend server

I am currently trying to implement a similar functionality to the example provided at this link in my Angular frontend application. The goal is to send a GET request to my backend with the search parameter obtained from an input field. However, even thoug ...

Retrieve the initial token from a union, referred to as an "or list," in Typescript

Is there a way to define a generic type F with the following behavior: type X = F<'a'|'b'|'c'> should result in X being 'a'. And if type X = F<'alpha'|'beta'|'gamma'|'del ...

"Invalid operation" error encountered within a Flask function in Python

I am trying to store a 'person' resource in a .ttl file using a JavaScript function: Here is my SPARQL query: @app.route('/registraAnnotatore/<author>+<mail>', methods=['POST']) def registraAnnotatore(author, ...

Images in a horizontal dropdown selection menu

Currently, I have a traditional select dropdown that is data-bound with Angular. <select class="form-control" ng-model="category"> <option value="work">Work</option> <option value="home">Home</option> <option valu ...

What is the best way to configure an EmailId validator in Angular 6 to be case insensitive?

My register and login page include a form validator pattern matching for the registration form. this.registerForm = this.formBuilder.group({ firstName: ['', Validators.required], emailId: ['', [Validators.required, Validators.patt ...

Node: How can I retrieve the value of a JSON key that contains a filename with a dot in

I have a JSON file named myjson.json, with the following structure: { "main.css": "main-4zgjrhtr.css", "main.js": "main-76gfhdgsj.js" "normalkey" : "somevalue" } The purpose is to link revision builds to their original filenames. Now I need to acce ...

Is there a way to dynamically adjust the form action based on whether or not JavaScript is enabled?

Is there a way to make a form default to calling a JavaScript ajax function for output, but switch to a PHP page if the user doesn't have JavaScript enabled? <form class="form-inline" role="form" action="javascript:search();"> <div class=" ...

A guide to resizing images in Node.js prior to using the writeFile function

var file_path = files.file.path; fs.readFile(file_path, function (err, data) { fs.writeFile(file_path, data, function (err) { res.end(JSON.stringify({ message: 'file uploaded successfully', success: true }); }); }); I exp ...

The formBuilder controls' setValue() and patchValue() methods are not functional when called within a method of a Cordova plugin

In developing my Ionic tabs app, I have integrated the cordova-plugin-datepicker and utilized Angular Material to design the form fields. One issue I encountered is setting the text input's value with the date obtained from the plugin’s calendar in ...

Identifying clicks on various indices within a common class or element

My website has a navigation menu with unordered list items in it. <nav> <ul> <li id="zero"></li> <li id="one"></li> <li id="two"></li> </ul> </nav> I am working on implementing J ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

When the mobile navigation bar is tapped, it remains open instead of closing

The persistent challenge of the mobile navbar failing to close upon clicking an item continues to baffle. Numerous attempts from Stack Overflow and even tweaks recommended by ChatGPT have been futile in resolving this issue. Despite trying alternative me ...