How can I replicate a div in Angular 6 using typescript?

I'm currently working on a project focused on providing detailed information about various vehicle components. Each component consists of specific descriptive fields. One feature I'm looking to implement is an "Add another component" button that will duplicate an existing div container with all its associated fields. Of course, the duplicated parent div should have a unique ID. Here's an example:

Within the component's HTML file:

<div id="component-outer">
    <div class="component-inner">
         Component Content....
    </div>
</div>
<button type="button" (click)="clone()">Add Another Component</div>

In the component's TypeScript file:

export class AppComponent {
    clone(){
         Need to clone #component-outer div and append below the last instance 
         of that div, then append the div name on the cloned element.
    }
}

While I typically use JavaScript/jQuery for cloning elements, I'm struggling to find the best approach to achieve exactly what I need in Angular. Would cloning be the appropriate method in this case?

Answer №1

To display items from an array as DOM elements, you can utilize the *ngFor directive in Angular.

<div id="component-outer">
    <div *ngFor="let item of items" class="component-inner">
         Component Content....
    </div>
</div>
<button type="button" (click)="append()">Add Another Component</div>

export class AppComponent {
     public items: any[];

     public append() {
          this.items.push({
              // values depend on what an item is
          });
     }
}

This concept is explained in the initial chapter of the first tutorial outlined in the documentation.

Reference link for more details on using *ngFor with 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

Exploring the capabilities of the hardware camera in Angular 2

Struggling to implement the tutorial in Angular2. The challenge lies in making navigator.mediaDevices.getUserMedia function properly. The error message indicates that mediaDevices is not recognized on type 'navigator'. Refer to the media capture ...

Unexpected object returned by the spread operator

Currently, I am utilizing node and specifically using babel-node. "start": "nodemon --exec babel-node --presets es2015 index.js" However, I have encountered an issue with my spread syntax in the following code snippet: export const login = async (parent ...

Unlock the Full Potential of TypeScript: Seamless Export of Classes and Functions

In my AngularJS project, I have a separate JavaScript file where I declare prototype functions. Here's an example: function lastConv(){ this.item1="2" this.message="hello" ...... } lastConv.prototype.setupfromThread(data) { this.currentBox = dat ...

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...

The getElementById() function is unable to locate any matches on the current page

Below is the HTML code I am working with: import { currentSlide } from './Carusel'; <div className='app__mainpage'> <div className='app__mainpage_banners'> <img id='app ...

What is the reason behind the continued existence of the @bazel/protractor npm package despite Protractor being marked as deprecated?

Curious about the reason behind including this line in the package.json build file of the Angular Material codebase. https://github.com/angular/components/blob/cb296970909fbec28470eeb64f162e26e2b6735b/package.json#L93 I recall hearing that Protractor was d ...

Instructions for printing a page and closing the Print window using Selenium

New to using Selenium: I tried the following code in Selenium to open the print window, but unfortunately it doesn't seem to work Keyboard keyboard = ((HasInputDevices)driver).getKeyboard(); keyboard.pressKey(Keys.ENTER); keyboard.pressKey(Keys.ch ...

The ng-view directive within AngularJS appears to be malfunctioning

I am facing an issue with my simple Angular app. I have two links that are supposed to change the URL and display the correct view within the same single page application. However, when I include the controllers' module in the main module, it stops wo ...

Issue encountered: Unable to locate module due to error: Unable to resolve 'crypto' in 'C:UsersmonkeDocumentsEpiconesb-ui ode_modules eflect-metadata'

I am encountering an issue with the reflect-metadata package while working on Angular 13. When attempting to use reflect-metadata, I am getting a strange error message stating "Module not found: Error: Can't resolve 'Crypto' in '*\ ...

The selected data is not being displayed

My input field is not displaying anything. Below is the script function in my view: <script> var Features = []; function LoadFeatures(element) { if(Features.length === 0) { $.ajax({ url:'@Url.Action("GetFeatures"," ...

Synchronizing the call of various views in an Angular application

I'm currently working on an angular single page application with a specific structure in mind. "app.parent - main parent state" "app.parent.childState - child state" "app.parent.childSatate" includes 4 different named views. My goal is to display so ...

Verify if the key-value pair can be found within a multi-layered object

Is it feasible to identify the existence of a key/value pair in any type or level of object, regardless of its structure being unknown beforehand? For instance: Pair to find: "kod": "REVH" Object: { "names": [{ "name1": "xxx", "name2": "yyy", ...

Blend field and JavaScript functions while retrieving data from MongoDB

Take a look at this information: { "creation_date" : ISODate("2015-02-10T03:00:00.000Z"), "days_of_validity": 10 } I need to find all documents where "creation_date" is less than today - "days_of_validity" This is what I have come up with so far: doc ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

Starting from TypeScript version 5.6, `Buffer` cannot be categorized as either `ArrayBufferView` or `Uint8Array | DataView`

Struggling to make the transition to TypeScript 5.6 Beta, I am encountering these error messages within the node_modules directory. Without making any other modifications, how can I resolve these errors? node_modules/@types/node/buffer.d.ts:632:19 - error ...

Showing the previous value in the Select2 select function

I have integrated Select2 as a searching dropdown feature on my website, but I am facing an issue where the previously selected value keeps being displayed even after selecting a new item from the list. Initially, I initialize the Select2 dropdown like th ...

AngularJS: The `$locationChangeStart` event

I am attempting to check the next token in the next, but I am encountering an error: TypeError: next.localStorage is not a function APP.JS .run(function ($rootScope, $location,$log,User) { $rootScope.$on("$locationChangeStart", function (event,nex ...

Convenient method for extracting the final element within a jQuery section

I need to determine whether the div with the class "divclass" contains an anchor tag. If it does, I have to run a specific block of JavaScript code; otherwise, no action is required. <div class="divclass"> <span> some text</span> ...

JavaScript filename

This question may appear simple, but I believe the answer is not as straightforward. Here it goes: Should I keep the filename of jQuery as "jquery-1.3.2.min.js" for compatibility reasons, or should I rename it to jquery.js? In my opinion, it's best ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...