Angular-4: Exploring Component Reference on Click Event

One of my challenges involves dynamically adding different components when the user clicks, allowing them to add and remove any component. However, I am struggling to figure out how to reference the component where the user clicked in Angular-4. here are some sample components that are loaded in app.component.ts:

@Component({
  selector: 'question-paragraph',
  template: `<div class="form-group container">
    <textarea></textarea>
  </div>`,
})
export class QuestionParagraphComponent { }

@Component({
  selector: 'question-image',
  template: `<div class="form-group container">
    <form enctype="multipart/form-data" action="" method="post">
      <p>Upload Image</p>
      <input type="file" name="uploaded_file[]" />
    </form>
  </div>`,
})
export class QuestionImageComponent { }

Below is the function that adds these components:

if (item=='question') {
      this.addService.appendComponentToBody(QuestionDetailComponent);
      this.removeComponent(this.sg[this.sg['question_id']]);
    } else if (item=='image') {
      this.addService.appendComponentToBody(QuestionImageComponent);
      this.removeComponent(this.sg[this.sg['question_id']]);
      let componentRef = this.addService.appendComponentToBody(QuestionTypeComponent);
      this.sg['ComRef'] = componentRef;
    }

I have a function to remove the component, but it requires knowing the component's reference:

removeComponent(componentRef){
    this.appRef.detachView(componentRef.hostView);
    componentRef.destroy();
  }

If anyone knows how to get the reference of a component on click, I would greatly appreciate your help. Thank you.

Answer №1

When dynamically adding a component, it is typically done so as a child of another element. By utilizing @ViewChildren, you can specify where within your component you want to reference and interact with its children. The second parameter, which is of type ViewContainerRef, allows you to access dynamically added children:

 @ViewChildren(DynamicComponent, { read: ViewContainerRef }) components: QueryList<DynamicComponent>

Another approach would be to utilize the return value from the createComponent method.

LATEST UPDATE: You can also monitor changes to your components' references by subscribing to them:

this.components.changes().subscribe(x=> console.log(x));

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

Update the function's argument type signature if the current argument is a function with properties

Looking for input on a potential title change, but for now, here are the details of my specific use case: I'm currently developing a library that facilitates executing methods remotely and accessing properties across serialized boundaries like those ...

Is there a way to determine the total number of angular components in my app using IntelliJ IDE?

Seeking a way to determine the total count of angular components using IntelliJ IDE. I attempted 'find in files' search tool with the terms "export class" but it retrieved more than just component files. Appreciate any help! =) Etienne. ...

Is it necessary to reload the page each time to see updates on the navbar in nextjs?

I recently developed a Next.js application with a Navbar component integrated into my layout.tsx file. The challenge arises when a user logs in and is redirected to the home page, which showcases a link in the Navbar for viewing their profile. However, I n ...

The ES6 reduce method is not giving the expected result

In Image 1, the output you will see if you log the final array from Snippet 1. My goal is to transform my array to match the format shown in Image 2. I attempted using lodash's _.uniqBy() method [Snippet 2], but the logged output of the reduce varia ...

Swap out a collection of objects for a different collection of objects

I need to replace the content of array1 with the content of another array2 while keeping the same references and indexes in array1: let array1 = [ { book : { id : 2, authorId : 3} } , { book : { id : 3, authorId : 3} }, { book : { id : 4, authorId : ...

Error in Angular: Running the Angular CLI outside a workspace prohibits the use of this command

I recently started learning Angular and am having trouble generating new components. When I opened the Integrated Terminal in the folder where I want to create it ng generate component modulo an error message popped up: Error: This command is not availabl ...

Best practice for managing asynchronous calls and returns in TypeScript

I’ve recently started working on an Ionic 4 project, delving into the realms of Javascript / Typescript for the first time. Understanding async / await / promise seems to be a bit challenging for me. Here’s the scenario: In one of the pages of my app ...

In Typescript, if at least one element in an array is not empty, the function should return false without utilizing iterators

My current approach involves receiving a string array and returning false if any of the elements in the array is false. myMethod(attrs: Array<String>) { for (const element of attrs) { if (!element) { return false; } } ...

Is there a way in Typescript to filter for the first instance of a unique object in an array of objects?

Having an array of JSON objects like this, the task is to iterate through it and retrieve the first occurrence of 'appname', such as 'app1' or 'app2', and store the entire object for each... myArray[ { ...

Class with abstract properties that are defined by its child classes

Is there a way to use TypeScript's abstract class to enforce defining functions and variables within the class for implementation? abstract class Animal { sound: string; speak() { console.log(this.sound); } } class Cat extends Animal { s ...

Utilizing TypeScript to Retrieve the Parameter Types of a Method within a Composition Class

Greetings to the TS community! Let's delve into a fascinating problem. Envision having a composition interface structured like this: type IWorker = { serviceTask: IServiceTask, serviceSomethingElse: IServiceColorPicker } type IServiceTask = { ...

The error message "Unable to access property MyToast.java as it is not

I've been diligently following this tutorial on how to write Java code in NativeScript and use it directly in TypeScript. But, unfortunately, I encountered an error message stating: Cannot read property 'MyToast' of undefined app.component ...

Using Angular-Meteor to make an HTTP request

I'm attempting to utilize the HTTP.call method with angular-meteor. Within my API backend folder, I am trying the following within a method: this.unblock(); try { const result = HTTP.call('GET', 'https://api.foursquare.com/v2/users/ ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

Using TypeScript to apply a typed decorator function to a subclass

I've taken on the challenge of creating a node.js and MongoDB ORM library similar to "Entity Framework" using TypeScript. This library will allow users to define a Model class (e.g. Person) that extends a Base class. The class decorator will enhance ...

Tips for choosing and unchoosing rows in angular 6

I am looking to extract the values from selected rows and store them in an array. However, I also need to remove a row from the result array when it is deselected. The issue with my current code is that every time I click on a row, the fileName values are ...

Tips for integrating CKEditor into an Angular 4 project

To start using CKEditor, I first installed it by running the command npm install ng2-ckeditor. Next, I included ckeditor.js in my index.html file. I then imported { CKEditorModule } from 'ng2-ckeditor'; in my app.module.ts file. After setup, I ...

Angular2 - Transmitting validation information from parent component to child component input validation

I am currently developing an automatic word correction module using Angular2. Within my child component, I have set up an EventEmitter. import {Component, Input, Output, EventEmitter} from '@angular/core'; ... export class StudyThumbsComponent{ ...

A window that pops up in Angular 2

I'm in the process of developing a popup window that requests login details when a button is clicked. Here's what my app.component looks like: import { Component } from '@angular/core'; @Component({ selector: 'my-app', ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...