Issues with accessing view variables within a directive query are persisting

I am struggling with a specific directive:

@Directive({
  selector: '[myDirective]'
})

export class MyDirective implements AfterViewInit {
  @ViewChild('wrapper') wrapper;
  @ViewChild('list') list;

  ngAfterViewInit() {

    // At this point, both of these are undefined 
    console.log(wrapper, list);
  }
}

This directive is designed to search for variables within the view in which it is applied.

For instance, if I have a template inside one of my components, MyComponent:

<div #wrapper myDirective>
  <ul #list></ul>
</div>

The issue arises when the directive fails to locate these variables based on its current setup. It seems that because the directive itself does not possess a view, the ngAfterViewInit method executes too early and/or the @ViewChild decorator searches for wrapper and list in the wrong scope.

Do you know how I can modify the directive to properly find these variables?

Answer №1

If you switch ViewChild to ContentChild, it is likely to solve the issue.

export class MyDirective implements AfterViewInit {
  @ContentChild('wrapper') wrapper;
  @ContentChild('list') list;

  ngAfterContentInit() {
    console.log(this.wrapper, this.list);
  }
}

Check out this Plunker example for reference

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

Issue: Unable to call method "call" as the model "Model" has not been initialized within a Sequelize instance. Kindly ensure that "Model" is added to a Sequelize instance before attempting to use the "call" method

Author.ts import {Table, Model, Column, DataType} from 'sequelize-typescript' @Table export class Author extends Model<Author> { constructor(){ super(); } @Column(DataType.STRING) fname: string @Column(DataType.STRING) lname: strin ...

Modifying the color of a specific div using jQuery

I am attempting to develop a function that changes the background color of a div when a user clicks on it and then clicks on a button. The value needs to be saved as a variable, but I'm having trouble getting it to work because it keeps saying that th ...

Can you explain the use of the 'this' keyword in map() and call() functions?

Recently, I've been revisiting my understanding of how to use call() and map() with a NodeList in JavaScript. It was quite easy to find information on how call() works, and there are plenty of examples of how it can be used with map(). However, whil ...

Establish a timeout period when using the hover function

My dynamically loaded content requires a specific method of invocation due to its unique nature. While the process runs smoothly without using a setTimeout, is there any way to introduce a 0.25 second delay in this scenario? Check out this fiddle for ref ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

How can you use a single parameter in a JavaScript function to swap the values of two numbers

Here's the challenge I'm facing: I need to create a function that will output 5 when given a(0), and 0 when given a(5). a(0) = 5 a(5) = 0 It should look like this: Hint: Use the following function structure function A(num){} something ...

Switch modules based on user options

My goal is to process an array of image files. I have the option to select them randomly or one by one (queue) based on the configuration specified in the config.json. To start off, I create the processor and determine the appropriate image selection modu ...

Storing Data Locally in Angular with User Authentication

Using angular8, I encountered an issue where logging in with USER1 credentials, closing the browser, and then attempting to log in with USER2 credentials still logged me in as USER1. While adding code to the app component resolved this problem, I faced an ...

Organize the array of objects

Within my React state, I aim to rearrange a set of 3 objects by always placing the selected one in the middle while maintaining ascending order for the others. Currently, I utilize an order property within each object as a way to keep track of the sequenc ...

Using the Vuex getter to populate a component with data using the v-for directive

I am currently constructing a vue2 component, utilizing a vuex store object. The structure of the component is as follows: <template> <ul id="display"> <li v-for="item in sourceData()"> {{item.id}} </li ...

Error: Peer Dependency Not Fulfilled

Warning: The package @schematics/[email protected] has a peer dependency of @angular-devkit/[email protected], but it is not installed. You will need to handle the peer dependencies manually. I initially installed Angular CLI using npm instal ...

Creating a unique data attribute in Alpine.js - A step-by-step guide

I am looking to establish a custom attribute and modify the value when clicked. This is my current setup: <div x-data="{ colorred = true }"> <div @click="colorred = !colorred">set red state</div> </div> I ...

Having trouble launching myapp on the Android Studio emulator for Ionic 3

My current project involves using Ionic with Cordova to develop an app without any visible errors in the CLI. I am also utilizing Android Studio to emulate the app. In addition, I am relying on the Chrome inspect feature to monitor my app's behavior ...

I need to show the value of A$ in a React form input, but ensure that only the numerical value is

I'm currently facing an issue where I want to show the currency symbol A$ in an input field. <form [formGroup]="incomeForm" *ngFor="let field of incomeFields"> <mat-form-field fxFlex> <input matInput [value]="incomeForm ...

What is the process for including a task in the current method?

I've been working on building a web app similar to Google Calendar. I have successfully created the necessary objects and methods, but now I need to implement a feature that allows users to add tasks. My current idea is for users to input a task which ...

Converting JSON data into a Backbone Model

My current project involves utilizing backbone.js, and I have encountered a json data structure as follows: { first_name: 'David', last_name: 'Smith', family: [{father: 'David', mother: 'Rose', brother: ...

Styled-components is not recognizing the prop `isActive` on a DOM element in React

In my code, I have an svg component that accepts props like so: import React from 'react'; export default (props) => ( <svg {...props}> <path d="M11.5 16.45l6.364-6.364" fillRule="evenodd" /> </svg> ) ...

I prefer not to run the next.js SWR until after the initial rendering

Development Setup ・ next.js ・ typescript ・ swr This uses swr for communication purposes. I am looking to only trigger it when the query value changes. However, it is also being executed during the initial rendering. How can I prevent it ...

Code activates the wrong function

Below is a snippet of HTML and JS code for handling alerts: HTML: <button onclick="alertFunction()">Display Choose Option Modal</button> <button onclick="alertFunction2()">Display Veloce Modal</button> JS: function alertFunct ...