How to pass parameters from a directive to a child component in Angular

I am currently attempting to create a child component that can pass parameters using a directive, but I have not been able to find any tutorials on how to achieve this yet.

I have tried looking at some resources, such as this one on Stack Overflow: Get reference to a directive used in a component

Below is a snippet of my code:

This is the template from the parent component:

<child-component>
    <grand-child-directive [name]='Ghandy'></grand-child-directive >
    <grand-child-directive [name]='Ani'></grand-child-directive >
    <grand-child-directive [name]='Budi'></grand-child-directive >
</child-component>

This is the grand-child-directive directive:

@Directive({
  selector: 'grand-child-directive ',
})
export class gc{
  @Input() name:string;
}

This is my child-component:

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.scss'],

})

export class childComponent implements OnInit 

@ViewChildren(gc) gc: gc;

  constructor(
  ) {

  }
  ngOnInit() {
    console.log(gc.name)
  }
}

When I use console.log(gc.name), I get undefined instead of an array [Ghandy, Ani, Budi]. Any help would be greatly appreciated.

Answer №1

It is recommended to utilize ContentChildren rather than ViewChildren. Additionally, you can implement the AfterContentInit lifecycle hook to retrieve the value.

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.scss'],

})

export class childComponent implements OnInit, AfterContentInit 

 @ContentChildren(GrandChildDirective) gc: QueryList<GrandChildDirective>;

  constructor(
  ) {

  }
  ngAfterContentInit() {
     console.log(this.gc.toArray().map(item => item.name));
  }
}

Here is an example

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

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

How can I achieve a result using a floating label in a .ts file?

I'm facing a simple issue that I can't seem to figure out. The problem is with a floating label in my HTML file, as shown below: <ion-list> <ion-item> <ion-label floating >Username</ion-la ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

"Angular Chart.js Updates: Keeping Your Charts Up-to-

Have a question regarding the integration of chart.js in an Angular 11 environment. I am working with 2 charts. AppComponent.html: <div class="col-sm"> <canvas id="bl" ></canvas> </div> <div class="col ...

What is the method for declaring constructor functions as object properties in TypeScript?

I am facing a challenge with typing an object that has a property which is a constructor function. How can I properly define the type for this situation: interface MyObj { constructor: () => ({ init: () => void }) } const myObj = { construct ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

What is the method for setting autofocus to the first input element within a loop?

I am currently working on a loop to display inputs, and I would like to be able to add focus to the first input element when it is clicked. Does anyone have any suggestions on how I can select that first element and set autofocus on it? ...

Issues with FormsModule functioning incorrectly when used in a separate module other than the main App Module

Within my SharedModule, I have the FormsModule imported. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from &ap ...

Visibility issue with Angular 4 ngFor variable within specific child component

I'm facing an unusual issue that I need help with. I am using a simple ngFor loop in my template code and for some reason, the variable I am trying to access is visible everywhere inside the loop except for one particular subcomponent. It's stran ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

What's the best way to provide route access to the same menu for two distinct user roles using AuthGuard within Angular?

I developed an application that includes three different user roles: ROLE_USER, ROLE_MODERATOR, and ROLE_ADMIN as shown below: export enum Role { User = 'ROLE_USER', Moderator = 'ROLE_MODERATOR', Admin = 'ROLE_ADMIN&apo ...

What is the best way to retrieve JSON data from a raw.github URL and save it into a variable?

Suppose there is a JSON file named data.json on Github. The raw view of the file can be accessed through a URL like this: https://raw.githubusercontent.com/data.json (Please note that this URL is fictional and not real). Assume that the URL contains JSON ...

Import a Component Dynamically Using a Variable in AngularJS

I am attempting to dynamically load a component using a variable, but I keep running into an "Uncaught Error: Template parse errors". How can I achieve this successfully? <app-{{ this.plugin.component }}></app-{{ this.plugin.component }}> ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

Transferring data between a ComponentPortal within an Angular CDK

After attempting to implement the method described in a Stack Overflow thread on Angular CDK: How to set Inputs in a ComponentPortal, I've encountered issues with the deprecated PortalInjector without clear guidance on what to use instead. The depreca ...

Issue with Typescript Application not navigating into the node_modules directory

After attempting to load the app from the root directory of our server, it became clear that this was not a practical solution due to the way our application uses pretty URLs. For instance, trying to access a page with a URL like http://www.website.com/mod ...

Establishing the rotation attribute of an SVG circle to create an angular progress tracker

Exploring the code of an Angular component and came across how the r attribute for an svg circle is defined like this: [attr.r]="radius - stroke / 2" This seems to work, but I'm wondering why it's done this way. Isn't the r attribute suppo ...

Encountered difficulties in deploying functions on Firebase Cloud Functions

While developing the Firebase Cloud Functions, I organized the files based on each function. Unfortunately, numerous errors occurred during deployment. Error [debug] [2022-07-19T14:36:17.677Z] <<< [apiv2][body] GET https://us.gcr.io/v2/xxxxxx/gcf ...