Getting the component class from a native element reference in Angular: A step-by-step guide

I have an HTML Div element with angular component children inside the div. Somehow the angular template is like this.

        <mat-radio-group [(ngModel)]="selectedRadioValue">
          <div
            #radioButtonDiv
            *ngFor="let opt of getInputPayload(); index as optIndex"
          >
            <mat-radio-button [value]="opt">
              {{ opt.label }}
            </mat-radio-button>
            <ng-container *ngIf="someCondition === true">
              <app-my-component [attr]="opt.foo"></app-my-component>
            </ng-container>
          </div>
        </mat-radio-group>

I obtained the reference to the outer div element using @ViewChildren

  @ViewChildren('radioButtonDiv') radioButtonDiv: QueryList<ElementRef<HTMLDivElement>>;

How can I access the <app-my-component> component class within the radioButtonDiv QueryList?

I attempted to use querySelector() from the nativeElement of the outer div.

        this.radioButtonDiv.forEach((rbd, index) => {
          if (index === findIndex) {
            // Ignore the setTimeout.
            setTimeout(() => {
              const findChild = rbd.nativeElement.querySelector('app-formulir-medis-attribute');
            }, 500);
          }
        });

However, in the code above, findChild returns the nativeElement of the <my-component> Component and not the Angular component, making it difficult to access its attributes and properties. How do I obtain the MyComponent class from the above element ref?

Thank you!

Answer №1

To achieve this, you have the option to utilize ContentChild or ng-content tag. Here is a live example on StackBlitz.

Answer №2

If you want to access the <app-my-component> component class instead of the DOM element, you can utilize @ViewChildren with the component class as the selector.

For example, if the component class is named MyComponent, your code would appear like this:

@ViewChildren(MyComponent) myComponents!: QueryList<MyComponent>;

Check out this StackBlitz for a demonstration of this method.

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

Unexpected field error is thrown by Multer in Node.js

I am currently utilizing Angular with ng2-file-upload, and I have encountered an error: { Error: Unexpected field at makeError (C:\Users\cDotsp27598345\Desktop\Projects\ZeoliteGlobal\node_modules\multer\lib\mak ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

Angular's keyevent is acting similarly to a tab when the input field is disabled

I've encountered some strange behavior with my input field. Every time a user presses the enter or space key, I want to execute some actions. Once the key is pressed, I need to disable the field until the actions are complete. Pressing the *enter ke ...

Is it possible for a ngrx signal feature store to retrieve the state of the store that it is consuming?

I am interested in creating a feature store that can receive input or reference a state from the store which interacts with or consumes the store, such as the parent of the ngrx signal feature store. For instance, imagine I have a store named "withCounter ...

determine the position of the slides in Ionic/Angular

Hey there, I recently created some slides in Ionic and encountered an issue with the pagination numbers not displaying correctly. Here's what I've tried so far: https://i.sstatic.net/4FJ0y.png @ViewChild(Slides) slides: Slides; proposals: Prop ...

Using Angular 2 to toggle the visibility of a component when hovering over and moving away from it

I have developed a custom filtering component in Angular 2, which I have integrated into the table header. My goal is to show the filter when the mouse hovers over a specific span, and hide it when the mouse moves away. <th> <span class="headCol ...

Tips for waiting for an Http response in TypeScript with Angular 5

Is it possible to create a function that can retrieve a token from a server, considering that the http.post() method generates a response after the function has already returned the token? How can I ensure that my function waits for the http.post() call t ...

Angular 2 - Emulating Encapsulated Properties

Although I understand that it's best to test code by consuming it the same way it will be in production and therefore not directly dealing with private properties and methods, TypeScript is causing me some confusion. I have a user service. // user.s ...

How can I create and utilize a nested array within an ngFor loop?

*ngFor="let arr = ['foo', 'bar', 'sla']; let item of arr; let i = index;" Why does setting the instantiation of arr before let item of arr; result in an exception displaying [object Object]? Why am I unable to structure it th ...

What is the reason behind `ngAfterViewChecked` and `ngAfterContentChecked` being invoked twice?

import { AfterContentChecked, AfterViewChecked, Component } from '@angular/core'; @Component({ selector: 'app-root', template: '' }) export class AppComponent implements AfterViewChecked, AfterContentChecked { ngA ...

Angular mat-icon can render intricate pictures

Embarking on my journey with Angular, I have recently delved into the world of mat icons. While I have managed to create simple mat icons successfully, I find myself stumped when attempting to tackle more intricate designs. Take for instance the image belo ...

The error message "registerNgModuleType: Uncaught TypeError: Cannot read property 'id' of undefined" indicates that there is an issue

I am facing an issue with my Angular app repository. After cloning the repository, installing the node_module, and running ng serve, I encounter an error. Despite searching for numerous solutions, none seem to be effective. The app is built on Angular 8.1, ...

Unusual behavior and confusion encountered with loadChildren in Angular 7 routing

I've encountered a strange behavior while using loadChildren in my application and I'm quite confused about why it's happening. Here is the content of my app-routing-module.ts: const routes: Routes = [ { path: '', redire ...

Place the label and input elements next to each other within the form-group

My form group includes both a label and an input field <div class="col-md-12 form-group"> <label class="col-sm-2 col-form-label" for="name">Name</label> <input type="text" class="form-control" name="name" id="name" [(ngMode ...

Why does the alert modal I created in ShadCn automatically close as soon as I click on it?

There is an action that I created which displays a menu, and I implemented a function where if the user selects delete, a warning alert is shown before proceeding. However, the issue I am facing now is that when I click on the menu, the modal opens but imm ...

Angular's interaction with databases

Can Angular framework securely access MySQL databases, or is it necessary to send data to a PHP page for retrieval from a database in order to ensure security? ...

Customized IntelliSense naming for overloaded parameters with conditional tuple types

In TypeScript 3.1, I have a generic function with arguments of either (TInput, string) or (string), depending on whether the generic's type parameter TInput extends undefined. To achieve this, I'm utilizing the new generic rest parameters feature ...

Tips on preventing duplicate class properties when they are declared separately from the constructor and then initialized

Imagine you have a simple ES6 class and you want to avoid redundancy by extracting constructor parameters into a separate type. For example: type BarParams = { x: string; y: number; z: boolean; }; export class Bar { public x: string; public y: n ...

Most effective method for sending an HTTP Post request with a JSON body in Angular 9

Hi there, I'm currently working on a project that requires saving information from 3 text box fields. I've been struggling to figure out how to make a POST request with a JSON body. Here's what I have so far: I've been piecing together ...

Declarations for TypeScript in NPM packages

In order to streamline my development process with bun.sh using workspaces as npm packages, I have created a tool available here. However, I am facing two issues: After bun installing the 'core' packages from npm and testing a sample, I encounte ...