Creating a list of components for drag and drop with Angular CDK is a straightforward process that involves following

I am attempting to use Angular's CDK drag and drop functionality to create a list of components that can be rearranged. However, I am encountering an issue where the components are not being displayed correctly.

In my App.component.ts file:

import { RightSideCombinedComponent } from './right-side.component';
import { LeftSideComponent } from './left-side.component';
@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

innerComponenets: Array<any> = [
  RightSideCombinedComponent,
  LeftSideComponent,
  ];
constructor() {}

  ngOnInit(): void {
  }

  

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.innerComponenets, event.previousIndex, event.currentIndex);
  }

<div cdkDropList cdkDropListOrientation="horizontal" class="example-list" (cdkDropListDropped)="drop($event)">
            <div class="example-box" *ngFor="let item of innerComponenets"  cdkDrag>
                {{item}}
                </div>

The issue I am facing is that instead of displaying the components, their code is being shown on the screen. Here are some screenshots for reference: Before drag and drop: https://i.stack.imgur.com/g0AKe.png

During drag and drop: https://i.stack.imgur.com/zFU0G.png

After drag and drop: https://i.stack.imgur.com/8R0WQ.png

If anyone has any insights on how to resolve this issue, your help would be greatly appreciated!

Answer №1

array=[0,1];

<div cdkDropList cdkDropListOrientation="horizontal" class="example-list"
      (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let item of array" cdkDrag>
      <app-left-side *ngIf="item==0"></app-left-side>
      <app-right-side *ngIf="item==1"></app-right-side>
  </div>
</div>

Check out the code in this stackblitz

By using this method, you can easily swap the elements of the array [0,1], indicating to Angular which component should be displayed first.

NOTE: This technique is only useful if data is not stored within the components, as each drop will create new and initialized components.

Answer №2

When the variable {{item}} is used, it retrieves values from an array called innerComponents that contains constructor functions. These functions are made draggable by using the directive cdkDrag on a parent <div> element.

If you have a predefined list of draggable components, you can simply place them directly in the HTML code without the need for an array or *ngFor structural directive.

<app-left-side cdkDrag></app-left-side>
<app-right-side cdkDrag></app-right-side>

Answer №3

For a more thorough explanation, please provide additional details regarding the moveItemInArray code and your process of reaching this.innerComponents (specifically which hook was used and what type).

Based on the results, it appears that you may be hooking to the prototype rather than the instance of HtmlElement.

EDIT:

To clarify, you should instantiate components within the array. Instead of having prototypes of the right and left component in your array, you should create an array of INSTANCES of those components like so:

for (const component of innerComponents) {
     const componentRef = viewContainerRef.createComponent<componentModel or any>(component);
innerComponentsInstancesReferences.push( componentRef);
    }

The componentRef array containing INSTANCES is what you should use in ngFor. This way, the Templates / View will properly display the REFERENCED INSTANCES of the components. You are essentially informing the template to "display the instances of my components" instead of just the prototypes.

Please refer to the article: https://angular.io/guide/dynamic-component-loader

and componentRef type documentation: https://angular.io/api/core/ViewContainerRef

It is crucial to consider types when implementing this solution.

PS> It may also work if you utilize [ngFor] which would evaluate your component instead of using a string, potentially instantiating it. However, I cannot guarantee its effectiveness.

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

Unleashing the power of RXJS: Leveraging IntervalObservable coupled with the

I recently incorporated HTTP pooling into my Angular application using IntervalObservable and startWith for immediate activation. I'm curious to know if IntervalObservable waits for the initial/previous call to finish streaming data. Also, is there a ...

Conceal the choice when aria-expand is in a deactivated state

I'm currently facing a challenge with hiding an option in mat-select only when aria-expanded is false. In the dropdown menu, I have both "Select All" and "Deselect All" options. However, when the menu is closed, it displays "Deselect All" by default ...

Getting an Angular TypeError after upgrading to version 9? It seems that the property 'selectors' cannot be read from null

After upgrading my Angular app from v7 to v8 and then v8 to v9, I encountered an issue. My app works perfectly locally when I run ng serve, but when I build for production using ng build --prod and deploy the app, I get an error in the application's c ...

Angular4 - Div with ngIf doesn't respond to click event

I'm attempting to add a click event to a specific div. Within this div, there is another div that is dynamically generated based on a Boolean condition that I receive as input. Unfortunately, in this case, the click event is only functioning when clic ...

A guide on integrating ngrx-store with a canLoad guard for optimal functionality

Is this a recommended practice? Below is what I am attempting to do: I have two lazy loaded modules: ManagementModule and ConfigurationModule, with the following route configuration: const routes: Routes = [ {path: '', redirectTo: 'manag ...

Issue with Angular9-MatDatePicker: Unable to establish a connection with 'ngModel' as it is not recognized as a valid attribute of 'input'

Despite my efforts to implement ngmodel binding with matdatepicker, I am still encountering issues, even after reviewing multiple other posts on the topic. Here is a snippet of my HTML: <mat-form-field> <mat-label>Start Date</mat-label ...

Is using instanceof the most effective method to verify type in Angular?

When working with the model, we import Type1 and Type2. Using the TypeComp variable which is a union of Type1 and Type2. import { Type1, Type2 } from '.'; export type TypeComp = Type1 | Type2; In the some.component.ts file, the selectedData$ obs ...

I encountered a frustrating issue of receiving a 400 Bad Request error while attempting to install

I am currently in the process of installing Angular CLI using npm to incorporate Angular 4 into several projects. Unfortunately, I keep encountering a 400 Bad Request error. Has anyone else faced this issue before and found a solution? I have already searc ...

How to update Angular Material table dynamically after CRUD operation without needing to reload the page

Hello, I am currently using Angular (v.9) along with ASP .NET Core Web API and EF Core (v 3.1) to perform CRUD operations. I have a region component form which is used as a dialog, you can view it https://i.stack.imgur.com/6w7hO.png The HTML code for the ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

Type of value returned by Observables

When I send my request to the API and parse it using the map function, the following code is executed: // portion of service post(url: string, params): Observable<Response> { let requestUrl: string = this.apiUrl + url; return this.http.post(r ...

It appears that Jest is having trouble comprehending the concept of "import type"

We've just completed a major update to our monorepository, bringing it up to date with the following versions: Nx 14.3.6 Angular 14.0.3 Jest 28.1.1 TypeScript 4.7.4 Although the compilation process went smoothly after the upgrade, we encountered num ...

The 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

Deploying an Angular application on AWS EC2 without using nginx as a reverse proxy

Our team has been tackling the challenge of hosting an Angular application on AWS. A question has emerged: can we deploy the Angular application without relying on nginx? This inquiry arose when we successfully deployed a node.js application without any ...

Angular component injected with stub service is returning incorrect value

While attempting to write tests for my Angular component that utilizes a service, I encountered an issue. Despite initializing my userServiceStub property isLoggedIn with true, the UserService property appears false when running the tests. I experimented ...

What could be the reason behind my Ionic app receiving a 401 error from an API call while Postman is not encountering the

Following the instructions from a tutorial on Smart of the Home, I implemented the code below in a provider for my Ionic 2 App. return new Promise(resolve => { // Using Angular HTTP provider to make a request and process the response let headers = ...

Release a new font on npm for integration into your project

In my current web-application project using angular2, I've designed a unique set of music glyphs such as notes, dotted notes, and time signatures. I couldn't find an existing font that suited my needs, so I created this custom font hierarchy: f ...

Choose a Spot on the Open Layers map using a marker or icon

As a beginner in the world of Open Layers, I'm eager to learn how to utilize markers or icons to obtain user location. Additionally, I hope to harness the power of Angular to extract these location details. ...

Utilize ngModel within the <p> element in Angular 8

Here is some HTML code for displaying card information: <div class="col-md-4" *ngFor="let card of allCards"> <p class="card-text">Card Color: {{card.color}}</p> <button type="button" class=" ...

Tips for implementing <mat-progress-bar> in .ts file when making API service requests with Angular

I'm currently utilizing an API call to retrieve an image from a service, and I would like to display a progress bar while the image is being fetched. It seems that I need to incorporate the progress bar within the service as the image data is returned ...