Having trouble adding dynamic components with drag and drop in Angular2, encountering an issue

These are my instructions for implementing drag and drop functionality.

Initially, I was applying my logic on click events to add a component to my div element. However, now I need to modify it to support drag and drop operations.

import {
    Directive, Output, EventEmitter, ElementRef, Input, Renderer, ViewContainerRef, ViewChild, ComponentResolver,
    ComponentRef
} from '@angular/core';
import {Div444} from "../gridmanager/div4-4-4.component";
declare var jQuery:JQueryStatic;

@Directive({
    selector: '[dnd_drag_grid]',
    host: {
        '(dragstart)': 'onDragStart($event)',
        '(dragend)': 'onDragEnd($event)',
        '(drag)': 'onDrag($event)',
    }
})
export class dnd_drag_grid {

    elementDrag:HTMLElement;

    @Input("drag") drag;

    set draggable(value:boolean) {
        this.drag = !!value;
    }

    elem:HTMLElement;

    constructor(private componentRef:ComponentRef, private resolver:ComponentResolver,
                private el:ElementRef, private renderer:Renderer) {
        this.renderer.setElementAttribute(this.el.nativeElement, 'draggable', 'true');
        this.renderer.setElementStyle(this.el.nativeElement, 'cursor', 'move');
    }

    onDrag(event:MouseEvent) {
        console.log("  -----onDrag---- " + this.drag);
        this.renderer.setElementStyle(this.el.nativeElement, 'border-style', 'dotted');
    }

    onDragEnd(event:Event) {
        console.log("  -----DragEnd---- " + this.drag);
        this.renderer.setElementStyle(this.el.nativeElement, 'border', 'none');

    }

    onDragStart(event:DragEvent) {
        console.log("  ----DragStart----- " + this.drag);
        this.elementDrag = this.el.nativeElement;
    }
}

@Directive({
    selector: '[dnd_drop_grid]',
    host: {
        '(dragover)': 'onAllowDrop($event)',
        '(drop)': 'onDrop($event)',
        '(dragleave)': 'ondragleave($event)',
        '(dragenter)': 'onDragEnter($event)'
    }
})
export class dnd_drop_grid {
    elementDrop:HTMLElement;

    @Input("drop") drop;
    @Input("target") target;

    set droppable(value:boolean) {
        this.drop = !!value;
    }
    
    set setTarget(value:string) {
        this.target = value;
    }

    elem:HTMLElement;
    @ViewChild('', {read: ViewContainerRef}) component_target;

    constructor(private componentRef:ComponentRef, private resolver:ComponentResolver,
                private el:ElementRef, private renderer:Renderer) {
        console.log("target "+ this.target);

    }

    onAllowDrop(event:DragEvent) {
        this.component_target = this.target;
        console.log("target "+ this.target);
        console.log("on allow drop ");
        event.preventDefault();
        this.renderer.setElementStyle(this.el.nativeElement, 'borderStyle', 'dotted');
        this.renderer.setElementStyle(this.el.nativeElement, 'borderColor', 'red');
    }

    ondragleave(event:DragEvent) {
        this.renderer.setElementStyle(this.el.nativeElement, 'borderStyle', 'bridge');
        this.renderer.setElementStyle(this.el.nativeElement, 'borderColor', 'white');
        console.log("target "+ this.target);
    }

    onDragEnter(event:Event) {
        console.log("target "+ this.target);
    }

    onDrop(event:DragEvent) {
        console.log("target "+ this.target);

        this.elementDrop = this.el.nativeElement;
        event.preventDefault();
        
        this.resolver.resolveComponent(Div444).then((factory) => {
            this.componentRef = this.component_target.createComponent(factory);
        });
        
        this.renderer.setElementStyle(this.el.nativeElement, 'borderStyle', 'bridge');
        this.renderer.setElementStyle(this.el.nativeElement, 'borderColor', 'white');
        
        console.log("Item has been dropped!");
    }
}

I have added the following code snippet in my HTML template:

<li dnd_drag_grid drag="true">Div 4-4-4</li>
<div dnd_drop_grid target="val" drop="true" class="page" id="content" size="A4" layout="portrait">
   <div #val hidden></div>
</div>

The error that I am encountering is:

Unhandled Promise rejection: _this.component_target.createComponent is not a function ; Zone: angular ; Task: Promise.then ; Value: TypeError: _this.component_target.createComponent is not a function(…)

Answer №1

targeting="value"

maps the value value to @Input("target") targeting;

I understand that what you are looking for is

[targeting]="valueVcr"

and in the main component

@ViewChild('value', {read: ViewContainerRef}) valueVcr:ViewContainerRef;`

to retrieve the ViewContainerRef from value assigned to targeting

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

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

Issue encountered when attempting to assign an action() to each individual component

I'm facing an issue with the button component I've created. import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-button', template: ` <ion-button color="{{color}}" (click)="action()"&g ...

Tips for integrating ng2-dragula into an Angular 2 project

How can ng2-dragula be implemented in Angular 2? Here's the code snippet, ****viewer.component.ts**** import { Component, Input, Output, EventEmitter } from '@angular/core'; import { Injectable } from '@angular/core'; import { ...

"Trouble with import aliases in a create-react-app project using craco: How to fix it

IMPORTANT UPDATE: Following Stackoverflow guidelines and for the convenience of everyone, I have created a concise reproducible example to showcase the bug in question: https://github.com/shackra/stackoverflow-alias-bug UPDATE 2: Just as an additional no ...

Tips for preventing circular dependencies when using combineSlices in Redux-toolkit

When utilizing combineSlices with createAsyncThunk condition, I find it challenging to avoid circular dependency. My store initiation thunk looks like this: thunk.ts export const initiateFx = createAsyncThunk< InitiatePayload, string, { state: R ...

Organize nested tuples and maintain their sequence

I am attempting to achieve a functionality similar to the following: type Type = object; type TypeTuple = readonly Type[]; function flattenTuples<T extends readonly (Type | TypeTuple)[], R = Flatten<T>>(...tuples: T): R { // code to flatten ...

Discover a demonstration showcasing login and registration functionalities by utilizing Flask, SQLAlchemy, Angular, and JSON

Hello everyone, I am new to Flask, SQLAlchemy, Angular, and JSON. Despite being a beginner in these technologies, I am working on building an application that utilizes them. Can anyone kindly share a small demo of a login and registration page with me or ...

Troubleshooting problem with Angular HttpClient when invoking Bing Maps Locations REST APIs

Currently, I have successfully implemented a Bing Maps call using Angular 4 Http service: this.http.get("{absolute URL of Bing Maps REST Locations, with options and key}") Now, I am trying to transition this call to use the newer HttpClient service in An ...

Every time I try to request something on my localhost, NextJS console throws a TypeError, saying it cannot read the properties of undefined, specifically '_owner'

Update: I've noticed that these errors only appear in Chrome, while other browsers do not show them. Recently, I created a simple NextJS project by following a couple of tutorials, which also includes TypeScript. However, after running npm run dev, I ...

"Learn how to trigger an event from a component loop up to the main parent in Angular 5

I have created the following code to loop through components and display their children: parent.component.ts tree = [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2', children: [ { ...

What are the steps for implementing the ReactElement type?

After researching the combination of Typescript with React, I stumbled upon the type "ReactElement" and its definition is as follows: interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor< ...

Strategies for Creating a Test Suite for RepositoryFactory in Vue.js/Nuxt.js

Summary of RepositoryFactory Implementation An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here hogeRepository.ts import { NuxtAxiosInst ...

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

Issues with Imported Routes Not Functioning as Expected

I am currently working on implementing routing in my Angular 2 project. All the components are functioning properly, but I encounter an error when I include 'appRoutes' in the imports section of app.module.ts. An unexpected TypeError occurs: C ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Troubleshooting webpack's compatibility issues with @ngtools/webpack for efficient Angular lazy loading

Lazy module is loaded eagerly with no separate chunks created for lazy modules To replicate the issue, I have created a repository 1. Clone the repository from https://github.com/sameerthekhans/lazy-load-angular-webpack-temp.git 2. Run npm i 3. Start t ...

The "keyof typeof Module" function is not functioning properly with interfaces

I am trying to create a custom dynamic type that represents a union of interface symbols from a file called "MyInterfaces.ts" export interface SomeInterfaceA {} export interface SomeInterfaceB {} ... export interface SomeInterfaceZ {} The definition I am ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...