Incorporating dynamic elements into *ngFor loops in Angular with custom style attributes

Incorporated the drag and drop feature following a tutorial on YouTube

Using *ngFor to create divs from the existing roomsFloorZone array, my goal now is to generate divs with style attributes based on values received from the backend response within the same *ngFor loop. All divs, whether from roomsFloorZone or backend response, should be contained under the same parent div.

I have experimented with the existing elements in roomsFloorZone.

import {Component, OnInit, AfterViewInit, Input, SimpleChange,
SimpleChanges} from '@angular/core';


@Component({
  selector: 'floor-zone',
  templateUrl: './floorzone.component.html',
  styleUrls: ['./floorzone.component.scss']
 })

export class FloorZoneComponent{

   urlFloorZoneIn: any;
   roomsFloorZoneIn: any;
   @Input() urlFloorZone;
   @Input() roomsFloorZone;
   @Input() currentBoxFloorZone;


 ngOnChanges(changes: SimpleChanges) {
    if (changes.urlFloorZone && changes.urlFloorZone.currentValue) {
        this.urlFloorZoneIn = changes.urlFloorZone.currentValue;
    }
    if (changes.roomsFloorZone && changes.roomsFloorZone.currentValue) {
        this.roomsFloorZoneIn = changes.roomsFloorZone.currentValue
    }
  }

  dropzone1 = [];

  currentBox?: string = this.currentBoxFloorZone;

  move(box: string, toList: string[]): void {
    box = this.currentBoxFloorZone;
        this.removeBox(box, this.roomsFloorZoneIn);
        this.removeBox(box, this.dropzone1);
        toList.push(box);

   }

   removeBox(item: string, list) { 
        if (list.indexOf(item) !== -1) {
            list.splice(list.indexOf(item), 1);
            }
    }
    }

Utilizing an existing array roomsFloorZoneIn for dragging and dropping elements in the following HTML where *ngfor is operational:

HTML

  <div id="toget" class="dropzone" [ngStyle]="{'width':'100%','background- 
     image': 'url('+urlFloorZoneIn+')','background-repeat': 'no-repeat',
     'background-position': 'center', 'background-size': '100% 100%', 
     'border':'1px solid black', 'height':'340px'}" appMovableArea 
     appDropzone (drop)="move(currentBox, dropzone1)">

       <div class="box" *ngFor="let box of dropzone1" appDroppable 
         (dragStart)="currentBox = box" appMovable>
        {{ box.dis }}
       </div>

   </div>

The aim is to assign style (transform attribute) and either "abc" or "def" to {{box.dis}} extracted from the code snippet below: [Have both style and node values readily available] and apply it to the *ngFor loop to position the div elements accordingly

 `<div xmlns="http://www.w3.org/1999/xhtml">
   <!--bindings={
   "ng-reflect-ng-for-of": ""
    }-->

    <div _ngcontent-c5="" appdroppable="" appmovable=""
      class="box draggable movable ng-star-inserted" touch-action="none"
      style="transform: translateX(183.2%) translateY(56%);"> abc 
      <span _ngcontent-c5="">X</span>
     </div>

    <div _ngcontent-c5="" appdroppable="" appmovable=""
      class="box draggable movable ng-star-inserted" touch-action="none"
      style="transform: translateX(183.2%) translateY(56%);"> def 
      <span _ngcontent-c5="">X</span>
    </div>

   </div>`

Therefore, the *ngFor loop should cater to existing elements (roomsFloorZoneIn) and allow for the insertion of additional elements fetched from the backend (using their respective style attributes and node values). Please note: The necessary style and node values are already accessible

Answer №1

In order for the two lists to be displayed sequentially, you can utilize two separate <div> elements, each with their own *ngFor directives referencing the two arrays:

<div class="myEnclosingDiv">
  <div class="firstList" *ngFor="let element of firstArray">
    {{ element.stuff }}
  </div>
  <div class="secondList" *ngFor="let element of secondArray">
    {{ element.otherStuff }}
  </div>
</div>

Alternatively, if the two lists need to be combined in some way, you can create a new array in your TypeScript file and iterate over it using a single *ngFor directive.

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

Angular 11 encountered an unexpected error: NGCC has encountered a failure

After upgrading my Angular application from version 10 to 11, I encountered a problem. Although the upgrade process was smooth, I am unable to run my application now. When I try to execute ng serve, I receive the following error: Error: Error on worker # ...

Angular: Utilizing the extend method in the child controller's scope

I am facing a challenge regarding the extension of methods in an angular child controller which is causing me some frustration. My main objective is to inherit all the public /$scope/ variables and methods from the parent controller into the child controll ...

Why is my Angular application showing the file path of the HTML file instead of displaying the content?

Just getting started with Angular here. I am working on a simple App that involves two components: the default app component and a second component utilized in the html-file of the app component. However, after running the app (check out the relevant file ...

Exploring the concept of making nested API requests within a route using Node.js and

Being a newbie in the world of coding, I'm excited to make my first post here. My current learning project involves developing a website that utilizes an external CRM for storing client data received from web forms. The storage functionality is up an ...

Executing data analysis scripts outside of the Angular zone

For my Angular website, I am incorporating various third-party scripts to gather analytics data. These scripts are loaded lazily and will attach event listeners (such as click events) to specific elements on the page. Typically, I would encapsulate this t ...

There is only a singular font awesome icon that appears properly based on the conditions set by [ngClass

I'm currently developing a user profile feature that allows users to submit links to their social media accounts. Each account is represented by a clickable icon, and the selection of which icon to display is based on various conditions within [ngClas ...

What is the best way to perform a single asynchronous or promise-based fetch request and utilize the retrieved data across multiple functions?

Is there a way to optimize fetching data from an API and use the fetched data in multiple methods within the same service without making redundant requests in the Network? export class MediaService { constructor(private mediaAppApiService: MediaAppApiS ...

Supply a JSON parameter as a variable into the .load() function

When a button is clicked, I am attempting to load a page using the .load() method with a POST request. The URL parameters are generated and displayed as JSON formatted in the button attribute btn-url. Problem: The parameter is not being passed to the .loa ...

What could be causing the input field to not have a border set?

I am attempting to add a border to my input field. I have successfully added the border to the text field, but it is being applied across the entire width. I would like the border to only appear on the input field up to where the characters start scrolling ...

The rotation transformation on the Z-axis occurs once the animation has finished

Currently, the rotation on the Z-axis is occurring after the animation, even though I am still in the early stages of creating an animated hand opening. The intention is for the fingers to only rotate on the X-axis to simulate a realistic hand opening moti ...

Performing a MongoDB aggregate operation to swap out a set of IDs with their corresponding objects from an array located within the same document

In my collection, I have a variety of documents that look like this: [{ id: 1, name: 'My document 1', allItems: [{ id: 'item1', name: 'My item 1' }, { id: 'item2', name ...

Error encountered when importing HTML

I am new to jQuery and currently learning it. I have the following code snippet, but unfortunately, my image is not loading for some unknown reason. When I try running the same link through my command line interface, the image shows up without any issues ...

showcase fresh material using the jquery fancybox

I have a fancybox popup using jQuery that is functioning as intended. Inside the popup, there is a link <a href="http://example.com/foo/bar.html">show another content of this fancybox</a> However, when you click on the link, the fancybox disap ...

Assistance required in resolving a JavaScript conflict with the jQuery Anything Slider

I am currently working on a website that already has a rotating header banner, but I am facing an issue when trying to add CSS-Trick's AnythingSlider to the body. After adding the AnythingSlider, the rotating banner stops working properly. You can vi ...

Tips for avoiding background color interference with raycaster

In my current three js scene, I have a ground, sky, and various objects. I want specific objects to change color to red when the mouse hovers over them, but not all objects should do this. Currently, everything I touch turns red, which is not what I want. ...

What is the best way to include special characters such as brackets [ ], single quotes ', and double quotes " in a MySQL database?

When I try to insert special characters using PHPmyAdmin, it works fine. But when I insert them via PHP, they don't seem to work correctly. Is PHP changing the special characters into something else? If that's the case, is there a way to ensure t ...

vertical lines alongside the y-axis in a d3 bar graph

https://jsfiddle.net/betasquirrel/pnyn7vzj/1/ showcases the method for adding horizontal lines along the y axis in this plunkr. I attempted to implement the following CSS code: .axis path, .axis line { fill: none; stroke: #000; } I am lo ...

JavaScript issue: TypeError - Information.map is not a function. Learn how to properly use .map method

Currently, I am learning how to use CRUD in React with Express and Node. I have successfully inserted data into the database, but I encountered an error when trying to represent the data using .map. You can see the issue with <Input onClick="{getCR ...

Incorporating prop types into default exported functions that are unnamed and anonymous - for example, "export default () =>{}"

Can you create propTypes for anonymously exported default functions like this: export default ({ name }) => <div>hi {name}</div>; //how do I do this part/ is it possible? ?.propTypes = { name: PropTypes.string }; EDIT: I tr ...

I encountered an issue: AxiosError {message: 'There was an error with the request, status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE'}

I have been working on a MERN stack web application that enables sellers to list their rooms for rent, allowing users to search and choose the ideal room for them. Whenever I try to use the Post Review functionality, I encounter the error "AxiosError {mes ...