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 child components of SequenceStep. In the parent component, the following declaration is present:

@ViewChildren(SequenceStep) steps: QueryList<SequenceStep>;

Then, I'm trying to manipulate these child components as follows:

ngAfterViewInit() {
    this.steps.changes.subscribe(steps => {
        console.log(steps);
    });
}

The issue that arises is:

metadata_resolver.js:639 Uncaught Error: Can't construct a query for the property "steps" of "Sequence" since the query selector wasn't defined.

Even though both Sequence and SequenceStep components have their selectors defined in their respective @Component decorators (sequence and sequence-step), this error persists.

What could possibly be the mistake I'm making here?

Answer №1

Did you attempt to include quotation marks in your @ViewChildren argument?

@ViewChildren('SequenceStep') steps: QueryList<SequenceStep>;

Answer №2

The problem may be connected to the importing of SequenceStep, so make sure to double-check the class name in the import statement.

Answer №3

Here are a couple key points to keep in mind:

  • When passing children from the outside, they are considered content and not children. The @ViewChild() decorator only works for children that are added directly to the component's template.

    The @ContentChildren() decorator is used for transcluded content:

    @ContentChildren(TheChild) kids: QueryList<TheChild>;
    
  • The this.kids.changes() method only notifies about changes after initialization. To handle this, access this.kids directly in ngAfterViewInit() and subscribe to get notified about any later changes.

    ngAfterViewInit() {
      this.myKidsCount = this.kids.length;
      this.cdRef.detectChanges();
    
      this.kids.changes.subscribe(kids => {
          this.myKidsCount = kids.length;
      });
    }
    
  • It's important to avoid causing changes during change detection in Angular. Trying to update this.myKidsCount within ngAfterViewInit() can lead to an exception because it is called by change detection itself.

To work around this issue, trigger change detection explicitly after updating the myKidsCount property:

constructor(private cdRef:ChangeDetectorRef){}

ngAfterViewInit() {
  this.myKidsCount = this.kids.length;
  this.cdRef.detectChanges();
}

Check out this Plunker example for further clarification.

Answer №4

Using @ViewChildren('SequenceStep') resulted in success for me. I was using Angular 4.X.X and Angular CLI 1.X.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

Adjusting box width based on device type: desktop and mobile

I'm currently working on a form that includes several mat-form-fields. I have set the width of these items to 750px, but this does not work well for mobile devices. I am trying to figure out how to make the form or mat-form-field automatically adjust ...

Troubleshooting Angular 2 Submodule Import Problem

I am facing an issue with a submodule that is using NgSemanticModule. The submodule works fine without the NgSemantic tags inside its components' templates, but fails when trying to use NgSemantic Components within the submodule. Interestingly, if I u ...

Guide to triggering an Observable depending on the result of a different Observable and obtaining an Observable as output

Looking to implement a service method in Angular 10 that returns an Observable for a custom User object. The goal is to have a service method that checks if the main service is running, and if not, return data from a local resource as an alternative. Pseu ...

How can I detect if a control value has been changed in a FormGroup within Angular 2? Are there any specific properties to look

I am working with a FormGroup that contains 15 editable items, including textboxes and dropdowns. I am looking to identify whether the user has made any edits to these items. Is there a specific property or method I can use to check if the value of any i ...

What steps can I take to prevent ng-bootstrap modal from automatically centering the content within the modal?

Looking for a solution to a UX issue with my Angular ng-bootstrap modal. The problem arises when displaying messages of varying lengths - if the message is longer than the screen's vertical resolution, it gets centered on the screen. This causes incon ...

Integration of HostConfig with AdaptiveCards

Is there anyone familiar with incorporating a HostConfig to style AdaptiveCards using the webchat CDN in an Asp.Net Core environment? For instance, what should be the name of the file? And where exactly does it need to be placed? The specific setup for ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

Tips for implementing a filtering function within an array of objects

I am struggling to implement a filter search feature in my ionic mobile application for an array of objects. The array is structured like this: initializeItems() { this.items = [ {Place:"Dumaguete city", date:"February 2 2018"}, {Place:"Sibulan", date: ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

Tips on looping through a dynamic FormControl using Angular2 and FormBuilder

I am facing an issue when trying to iterate over a dynamically generated FormControl in the HTML section. Instead of displaying the expected values, I am getting [object Object],[object Object] in the input field. Here is the provided data structure: { ...

Angular-CLI personalized schematics and collections

I am currently in the process of creating custom schematics for Angular CLI. After some experimentation, I have discovered that the "collection" needs to be compiled because the CLI cannot read TypeScript directly. This means that you can't simply clo ...

How can I implement dynamic styling for the rows in the PrimeNG table?

I have the MyObject.ts file with the following properties: name: String rowStyle: String In addition, I have a MyComponent.ts file containing: myObject1: MyObject = new MyObject(); myObject2: MyObject = new MyObject(); myObjectList: MyObject[] = []; myO ...

I'm currently utilizing CSS GRID to create a map layout, but I'm encountering an issue where the layout is not filling the entire screen. I'm wondering how I can achieve this in Angular

Here is the unique html code snippet for a layout that dynamically creates grids using json input: <!DOCTYPE html> <html lang="en"> <head> <title>Booking Page</title> </head> <body> <div ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

Having trouble with ng build optimization error in Angular?

While developing a real-time chat application using Angular 13, I encountered an issue when trying to build the app for testing on my Node.js web server: ng build Every time I run this command, I receive an error in the console. Here is a screenshot of ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

An error was encountered while parsing JSON data in Angular due to an unexpected token

I am currently working on implementing role-based authorization in my project. The goal is to hide certain items in the navigation bar based on the user's role. I encountered an error as shown below. How can I resolve this? service.ts roleMatch(a ...

The API endpoint code functions perfectly in Express, but encounters an error when integrated into Next.js

Express Code: app.get('/', async (req, res) => { const devices = await gsmarena.catalog.getBrand("apple-phones-48"); const name = devices.map((device) => device.name); res.json(name); }) Nextjs Code: import {gsmarena} ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...