Trying to access the TemplateRef in Angular2 leads to receiving an empty comment node

Struggling to create a custom sorting component in Angular2 because I'm unable to access a template variable. It's crucial for me to be able to reach the ng-template so that I can duplicate/stamp the element to generate drop zones based on the provided template.

I attempted using @ViewChild("dropzone"), but it just returns an empty comment node.

This is what the Component looks like:

@Component({
    selector: "my-sortable",
    template: `
        <ng-content select="my-sortable-content"></ng-content>
    `
})
export class SortableComponent implements AfterViewInit {

    @Input() //@ContentChild("dropzone")
    dzTemplate: any;

    onAfterViewInit() {
        // Returns an object but the 
        // nativeElement is an empty 
        // comment node
        console.log(this.dzTemplate); 
    }
}

And this is the corresponding HTML:

<my-sortable [dzTemplate]="dropzone">
    <ng-template #dropzone>
        <p>Hey, I'm a drop zone!!</p>
    </ng-template>
    <my-sortable-content>
        <div *ngFor="...">
            ...
        </div>
    </my-sortable-content>
</my-sortable>

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

Answer №1

After some exploration, I discovered the answer. It appears that within the ElementRef object lies a valuable method called createEmbeddedView(), which is capable of returning an instance of EmbeddedViewRef. With this newly obtained reference, I can conveniently access the DOM elements stored within the rootNodes property. Since these nodes are not yet associated with any specific element, they provide an ideal foundation for cloning or stamping purposes.

Answer №2

When I faced a similar task, I found myself resorting to using forwardRef from the angular core library.

import { Component, AfterViewInit, ViewChild, forwardRef } from '@angular/core';

/* ... in component somewhere */
  @ViewChild(forwardRef(() => SomeComponent)) // You can use a DI token I believe
  private paginationControls: SomeComponent;

Working with the any type might pose some challenges, but give it a try! :D You may also find the need to utilize injection tokens - although I'm not entirely certain...

If your requirements involve altering behavior based on template types, incorporating static typing and switching over dynamic strings or other criteria would be a more efficient approach. I've personally created a map linking componentIDs to component types and leveraged that to create new components using ComponentFactoryResolver - while this method involves listing out all scenarios, it could prove essential if you need to delve into component details within your sorting component (especially if forwardRef doesn't deliver as expected).

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

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Include an additional query parameter called login_hint in microsoft-adal-angular6 directly from an Angular component

Utilizing the provided package https://www.npmjs.com/package/microsoft-adal-angular6 for logging into azure AD has been successful. In the app module, I have configured the extraQueryParamter as shown below: MsAdalAngular6Module.forRoot({` tenant: " ...

Having trouble with UpdateMany in mongoose, but it works perfectly in mongodb when executed directly

I am attempting to update and insert data in mongoose. After sending some requests, I receive the following result: let obj = [ {name: aaa, age: 10}, {name: bbb, age: 11}, {name: ccc, age: 12}, ] My goal is to update all existing documents an ...

Issue with Angular 6 and Chrome: Event listener ($event) occasionally throws the error "unable to access property 'value' of null"

It appears that the buttons are being iterated correctly using ngFor, and upon inspection they have the correct attributes. However, when clicked, the function in the controller sometimes claims the parameter is 'undefined', happening randomly ab ...

Having trouble with RouterExtension.back() in Nativescript Angular?

I've created a module called TransactionModule that consists of the following routes: transaction-routing.module.ts export const routes: Route[] = [ { path: 'transaction', component: TransactionComponent, canActivate: [AuthGu ...

In Chrome, Angular http request returns null while in Firefox, it functions as expected

Recently, I encountered a strange issue while working on my Angular 7 project. For the past two months, everything was running smoothly without any problems. However, all of a sudden, I started getting null returned for all my HTTP requests in Chrome. Surp ...

What is the best way to display my images within Material UI Cards using React with Typescript?

I'm currently faced with a challenge of rendering images within Material UI's cards. I am successfully passing props to each card from a constants.tsx file where the heading, description, and bodyHeader are all properly read, but for some reason, ...

Angular material mat-calendar multiyear range selection视图

Experiencing an issue with a mat-calendar multiyear view. By default, the dropdown multiyear table displays 3 years back and 20 years forward from the current year (2016, 2017....2030). https://i.sstatic.net/tWSif.png Instead, I am looking to view 23 yea ...

Having trouble accessing @ViewChildren from the parent component

I've been facing an issue while attempting to control the child instances of a component and I can't seem to bypass this particular error. I've been referring to solutions provided on this specific thread. The main component Sequence houses ...

Tips for efficiently deconstructing JSON arrays, objects, and nested arrays

I'm attempting to destructure a JSON file with the following structure: [ { "Bags": [ { "id": 1, "name": "Michael Kors Bag", "price": 235, "imgURL" ...

The object might be undefined; TypeScript; Object

Why is it that the object may be undefined, even though it is hard-coded in my file as a constant that never changes? I've tried using ts-ignore without success. const expressConfig = { app: { PORT: 3000, standardResponse: `Server ...

Initiating modal function upon page load

I'm currently working with Ng2-modal and facing the challenge of triggering the myModal.open() function right when the page loads. When attaching it to a button (click)="myModal.open", everything functions properly. Despite extensive research, I' ...

I've added a check, so why is TypeScript still complaining about the possibility of my property being undefined?

const handleLinkClick = (index: number) => () => { const hasUrl = !!searchItems[index]?.url; if (hasUrl) { navigateToLink(searchItems[index]?.url); } else { setItemSelected(index); } }; However, the issue I encountered is: (property) ...

what is the process for incorporating a unique style in npm mydatepicker?

What is the best way to customize the style of npm mydatepicker? Here is the code I have been using: <my-date-picker [options]="myDatePickerOptions" (dateChanged)="onDateChanged($event)"></my-date-picker> Is it possible to modify its backgrou ...

You won't find ngModel as a property of "input" in Angular (don't rely on importing FormsModule to fix this)

I've exhausted all options but can't seem to get ngModel working in the component.html file. My form contains the following html: <input [ngModel]="username" type="text" name="username" [placeholder]="'INPUT_USERNAME_HINT' | transl ...

Local variables are now being refreshed with every modification in the data stored in Cloud Firestore

Having trouble maintaining the accuracy of my local variables in sync with changes to the data in cloud firestore. Specifically, in my local variable called count_vehicle, the value represents a count based on specific conditions from the data in cloud fir ...

The issue I encountered with Angular's Mat-Select component is that the openedChange

When a user opens the mat-select, I am attempting to set CSS style using custom code. However, I am encountering an undefined error. Upon checking in the console, I noticed that the panel value is returning undefined. Can someone please advise me on how to ...

Error: Unable to access the 'headers' property since it is null. MEAN stack issue

I'm in the process of developing a basic ToDoApp using the MEAN (Angular 2) stack, but I'm encountering an issue with the http.post request. Whenever I execute the post method, the current JSON object successfully gets added to the database. Howe ...

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

Resolving naming conflicts in Angular templates: what's the solution?

Within my application, I have created two essential components: JokesList Joke The JokesListComponent is structured as follows: template: <app-joke *ngFor="let joke of jokes" [joke]="joke"></app-joke> @Component({ sel ...