Having trouble importing a standalone directive into a standalone component

I am currently working on a directive that can capture the coordinates of the parent element and change the position of the child element based on the parent's x and y positions.

Both components are standalone, and the directive has already been imported into the component. However, I am encountering an error:

✘ [ERROR] NG8002: Can't bind to 'appMenuChildPosition' since it isn't a known property of 'ul'. [plugin angular-compiler]

So, how do I properly import the directive into the component? Oo

My component

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [NgIf, NgFor, TruncatePipe, LocaleConverterPipe, MenuChildPositionDirective],
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.sass'],
  animations: [fadeOut]
})
export class HomeComponent implements OnInit, OnDestroy {

  public isLoading: boolean = true;
  public settings?: Settings;
  public error?: HttpErrorResponse;
  private isDestroyed$ = new Subject<void>();

  constructor(
    private backendService: BackendService,
    private utilsService: UtilsService
  ) {}

  public ngOnInit(): void {
    this.backendService.get_settings()
      .pipe(
        takeUntil(this.isDestroyed$)
      )
      .subscribe({
        next: (data: Settings) => this.settings = data,
        error: (error: HttpErrorResponse) => this.error = error,
        complete: () => this.setup(this.settings)
      });
  }

  public ngOnDestroy(): void {
    this.isDestroyed$.next();
    this.isDestroyed$.complete();
  }

  public open(event: MouseEvent, element: NavigationElement): void {
    const parentElement = event.target as HTMLElement;
    const rect = parentElement.getBoundingClientRect();

    element.coords = {x: rect.left, y: rect.top};
    element.opened ? element.opened = false : element.opened = true;
  }

  private setup(settings?: Settings): void {
    this.isLoading = false;
    if (!settings) return;
    if (settings.account.bid) this.utilsService.saveItem('bid', settings.account.bid);
  }
}

My directive

@Directive({
  selector: '[appMenuChildPosition]',
  standalone: true
})
export class MenuChildPositionDirective implements OnChanges {

  @Input() parentX?: number;
  @Input() parentY?: number;

  constructor(private element: ElementRef) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['parentX'] || changes['parentY']) {
      this.adjustPosition();
    }
  }

  private adjustPosition(): void {
    console.log(this.parentX, this.parentY);
  }

}

My template

    <nav>
      <ul class="menu">
        <li *ngFor="let item of settings?.nav">
          <p class="link" *ngIf="item.children" (click)="open($event, item)">{{ item.name[0] }}</p>
          <a *ngIf="!item.children" [href]="item.name[1]">{{ item.name[0] }}</a>
          <ng-container *ngIf="item.children">
            <ul [class.hide]="!item.opened" class="popup-menu" [appMenuChildPosition] [parentX]="item.coords?.x" [parentY]="item.coords?.y">
              <li *ngFor="let sub of item.children">
                <a [href]="sub.name[1]">{{ sub.name[0] }}</a>
              </li>
            </ul>
          </ng-container>
        </li>
      </ul>
    </nav>

Answer №1

The reason for the error is due to the usage of the syntax [appMenuChildPosition]. This syntax indicates to the compiler that a directive called appMenuChildPosition is expecting input. To resolve this, simply remove the brackets and your code should work correctly!

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

Streaming the result of Long Polling on HttpClient directly into a CSV file

Query 1: Is there a way to modify the behavior to invoke callbacks instead of using Observable.interval? Specifically, I want the next call to be made only after receiving a response from the server, even if it takes longer than the specified interval (e.g ...

Learn how to access tag attributes within the ngIf function in Angular 2

considering this structure <a *ngIf="canAccess()" routerLink="/adminUsers">...</a> <a *ngIf="canAccess()" routerLink="/link2">...</a> <a *ngIf="canAccess()" routerLink="/otherlink">...</a> <a *ngIf="canAccess()" rout ...

I'm trying to troubleshoot this issue - the duration is showing up as NaN years, NaN months, NaN weeks, NaN days, NaN

Currently I am troubleshooting an issue in my ionic project. I have a button and I want to display the date that the user selects. This is my code: age.component.ts import { Component, OnInit } from '@angular/core'; import * as moment from &apo ...

Creating Observable in Angular 5视Render

As I attempt to display an Observable in Angular, I encounter an issue where nothing appears on the browser despite making a request to an API for data. Here is the service responsible for retrieving information about a single user: export class UserServ ...

Navigating to a specific node in a PrimeNG Tree component can be achieved by using

Looking for guidance on a feature in my PrimeNG tree and autocomplete setup. I want the tree to expand to the node that matches the text input from the autocomplete field, scrolling to and highlighting the selected node. I attempted expanding the tree by ...

swap out an element in an array with an extra element

My array contains elements with both id and des properties. I would like to add an additional property like value:0 to each object in the array. I achieved this using a loop. let data = [ { "id": 1001, "des": "aaa" }, { ...

Change a nullable string property within an interface to a non-nullable string property

Looking at two interfaces, one with a nullable vin and the other without: interface IVehicle { vin: string | null; model: string; } interface IVehicleNonNullVin { vin: string; model: string; } The goal is to convert a model from IVehicle ...

Obtaining IP Address with Jquery or Phonegap: A Guide for Cross Platform Development

Is there a way to retrieve the IP address using Jquery or Phonegap? I am currently working on an application that is compatible with Android, iPhone, and Windows platforms. I'm in need of a solution to locate the IP address of a request. ...

Encountering a fatal error "Segmentation fault: 11 bash -l -c ..." while attempting to compile a React Native app

My Objective While using react-native, running yarn run:ios to launch an existing app results in an error preventing it from working properly. Situation The current execution environment is as follows: System: OS: macOS 13.6 CPU: (8) arm64 Apple ...

To insert a new row into a table with an onClick function, along with removing this attribute from all other rows except for the newly added one

I recently created a piece of code that enables the addition of a new row and removes an (onClick) attribute when clicking on an existing row within a table. <table style="vertical-align:middle;margin:20px;" id="table_insert"> <tr id="tra" > ...

prevent communication between different domains

Is there a way to prevent other domains from sending POST and GET requests to my domain? I don't trust end users to refrain from doing so, especially considering that the same origin policy can be bypassed. Are there any effective methods for managing ...

npm WARNING: The package @angular-devkit/[email protected] is in need of a peer dependency xxxx, however no installation for this dependency has

Attempting to launch an angular project and encountering the following errors: $ npm install npm WARN @angular-devkit/[email protected] requires a peer of @angular/compiler-cli@^14.0.0 but none is installed. You must install peer dependencies yoursel ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

Unable to Delete Attribute in JavaScript

When I test the code snippet below in the Chrome console, it works perfectly fine. However, the code fails to work when I incorporate it into my JavaScript extension in Chrome. var region = document.getElementById("physicalDeliveryOfficeName"); region.rem ...

I'm facing a roadblock with installation of angular due to a permission denied

Error: Permission denied to access '/Users/gs/.npm-global/lib/node_modules/@angular/cli'', npm ERR! errno: -13, npm ERR! code: 'EACCES', npm ERR! syscall: 'access', npm ERR! path: npm ERR! '/Users/gs/.npm- ...

The program encountered an error while trying to access the undefined property '_header'

An issue arises when the app.use(express.static("web")) line is executed. var express = require('express')(); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //app.get(&apo ...

Ways to eliminate the top space in the background image

After implementing a basic HTML code to add a background image to my webpage, I noticed there is still some empty space at the top of the page. I attempted to adjust the position of the background image using the following code, but it only lifted it upwar ...

Unsupported geometry detected by ThreeBSP: Unable to process

note: Utilizing Three-CSG for the purpose of merging geometries in Three.js. An error is being thrown stating Uncaught ThreeBSP: Given geometry is unsupported when an instance of THREE.Mesh is passed into the ThreeBSP method of the library. Any insights ...

Encountering a "Module parse failed" error with type annotations in Nextjs while using Yarn Workspaces

I decided to experiment with transitioning a project from using Vite and React to Next.js and React. After reviewing the documentation on this page: https://nextjs.org/learn-pages-router/foundations/from-react-to-nextjs/getting-started-with-nextjs I made t ...

I'm struggling to position the four divs in each of the two rows similar to the example provided. Can anyone help me figure this

I need help figuring out how to position 4 divs in a row so that when one is clicked and expands with additional information, it pushes the bottom div down. All 8 divs have the same class. I attempted using display: inline-block, but all the lower 4 divs m ...