Trouble loading data with ContentChildren when querying RouterLink and RouterLinkWithHref

I've been working on a custom Structural Directive inspired by the functionality of the RouterLinkActive directive.

To get started, I followed the example for the UnlessDirective and incorporated elements from Angular's RouterLinkActive directive, specifically where it uses the ContentChildren decorator to access child components.

// TODO(issue/24571): remove '!'.
@ContentChildren(RouterLink, { descendants: true })
links !: QueryList<RouterLink>;

// TODO(issue/24571): remove '!'.
@ContentChildren(RouterLinkWithHref, { descendants: true })
linksWithHrefs !: QueryList<RouterLinkWithHref>;

This is what my template currently looks like:

<p *appUnless="false">
    This paragraph is displayed because the condition is false.
    <a routerLink="/another-page">my link</a>
</p>

In an attempt to retrieve the links, I added the following method:

ngAfterContentInit(): void {
    console.log("links length", this.links.length);
    console.log("linksWithHrefs length", this.linksWithHrefs.length);
}

However, the issue I'm facing is that the links and linksWithHrefs arrays remain empty. Can anyone point me in the right direction? Here is the link to the full code. My Angular version is 7.

Answer №1

There are a couple of issues, with one specifically related to how your directive is implemented:

  1. Firstly, you forgot to import RouterModule and neglected to call forRoot(...) in your root module. This means that the anchor in your root component template lacks binding to an instance of RouterLinkWithHref.

  2. Secondly, because your directive is structural, you cannot query for content children. The language can be a bit confusing here, so I will need to do some further research and update my answer later.

For now, if you refactor your directive to be simply an attribute as shown in this stackblitz example, it should work as intended.

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

Combining numerous interfaces into a unified interface in Typescript

I'm struggling to comprehend interfaces in Typescript, as I am facing difficulty in getting them to function according to my requirements. interface RequestData { [key: string]: number | string | File; } function makeRequest(data: RequestData) { ...

Which is better: NgSwitch or ComponentFactoryResolver?

Currently, I am developing an application that showcases various users and once a user is selected, an information page specific to their type is displayed. There are approximately 20 different types of users, each requiring a unique layout and functionali ...

Angular - The parameter type '(error: any) => void' cannot be assigned to the type '() => void'

I encountered an issue with my error handling code in Angular-11: return this.api.post('auth/user/login', data, headers).subscribe( (result: any) => { console.log(result.message); console.log(result.code); if ...

Is there a feature in Angular 2+ (specifically Angular 7) that allows for comparing code differences

Is there a code comparison component or plugin available for Angular 2+ (specifically Angular 7) that can compare two separate text files? In our current AngularJS application that we are upgrading, we currently use Ace-Diff and it works effectively. Howe ...

Retrieve form input from a different component's form using React Hook Form

Currently, I am facing an issue with two React components that contain identical form fields. The challenge is to synchronize a checkbox in one component with the input from the form in the other component when it is checked. This functionality is similar ...

Why does Ava.js only display error logging in our CI environment and not locally?

I am encountering a failing Ava test that should produce the following error: $ npm run test > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0167647562695e626e747372647241302f31123f352b">[email protected]</a> ...

Issues with the pushState feature on the Angular platformLocation

When the platform is loaded for the first time, I want to inject a new state into the browser history so that when the user clicks the back button, they are taken to the home page of the app. I have attempted to add a new state using: 1. PlatformLocation ...

Utilize a specified router outlet for loading a module lazily or for child modules

I am working on a project where I need to load pages with a configuration bar at the top. Each page will have a unique configuration setup that is specific to that page. In my app.component.html file, I have defined the following: <router-outlet name= ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

The element Component is not recognized even after importing the module and applying the CUSTOM_ELEMENTS_SCHEMA schema

Recently, I integrated PinchZoom into my Angular 6 project as a node module called ngx-pinch-zoom. It's important to mention that my project is also based on Ionic 4. Within my app.module.ts file, I imported the PinchZoomModule and included CUSTOM_EL ...

The Validation Library known as 'Yup' encounters compilation issues with TypeScript

After deciding to utilize the Yup library for form validation in my project, I encountered a persistent and confusing library error each time I tried to install it. This issue has been plaguing me despite numerous attempts to troubleshoot. Any suggestions ...

Testing the inner Observable of mergeMap in RxJS

Here is the code snippet that I am working with: createAsset(asset: Asset): void { this._assetsService.uploadFile() .pipe( mergeMap(_ => this._assetsService.createAsset({ ...asset, extension: 'png' })), ...

Error encountered in Angular 2 due to an unexpected token

After updating nodejs, I encountered an error with Angular 2 that was working fine before. Now, after updating the node_modules, it has stopped working and I am unsure of where the error is or how to fix it. (index):29 Error: (SystemJS) Unexpected token & ...

The Microsoft Bing Maps V8 TypeScript library is unable to load: "Microsoft is not recognized."

I'm looking to integrate BingMaps into my React project using TypeScript. After installing the npm bingmaps package, I have included the necessary d.ts file. To import the module, I use the following code: import 'bingmaps'; Within my Com ...

Error: Angular 2 Missing Required Dependency - @angular/core version 2

I am a beginner in AngularJS2 and I am looking to incorporate a server-side datatable in my application. To achieve this, I have utilized the following command: npm install --save ng2-smart-table library However, when executing this, an error is encoun ...

"Utilize Tuple in TypeScript to achieve high performance programming

I've been delving into TypeScript, focusing on the tuple type. As per information from the documentation, here is the definition of a tuple: A tuple type is another form of Array type that precisely knows its element count and types at specific posi ...

Encountering an issue with Angular2 while attempting to map data from a WebAPI (Error: Unable to perform data differentiation

I've been struggling to retrieve data from an API and display it in a list using ngFor. I've experimented with promises, observables, map, subscribe, async pipe, but haven't had any success. It seems like the API is being called, but I keep ...

What is the best way to incorporate single quotes within a string literal in JavaScript when constructing SQL queries?

Currently, I am developing a SQL query using Javascript where I pass values. If any value is undefined, I want it to be passed as null. This is how my code looks: const sql = `INSERT INTO MYTABLE( COLUMN1, COLUMN2 ) VALUES( ${param.value1 ?? null}, ...

Encountering issues with Angular component test cases: receiving a Type Error stating it cannot read the property "contractno" as it is undefined

When attempting to inject the default dependency required to run the spec file without errors, I encountered a Type Error: Cannot read property "contractno" of undefined. /** This is the userModel Class **/ export class UserModel { contractNo: string; ...

Can you explain the functionality of `property IN array` in the TypeORM query builder?

I'm looking to filter a list of entity ids using query builder in an efficient way. Here's the code snippet I have: await this._productRepo .createQueryBuilder('Product') .where('Product.id IN (:...ids)', { ids: [1, 2, 3, 4] ...