Using a template reference variable as an @Input property for another component

Version 5.0.1 of Angular

In one of my components I have the following template:

<div #content>some content</div>
<some-component [content]="content"></some-component>

I am trying to pass the reference of the #content variable to SomeComponent using @Input()content, but I'm unsure of the variable type.

After researching online, it seems that it should be ElementRef, so I tried the following:

  @Input()
  component: ElementRef;
  ngOnInit() {
    console.log(this.component); // this prints the html element on console
    console.log(this.component.nativeElement); // this prints undefined
  }

However, this.component.nativeElement returns undefined.

Further testing revealed that this.component is actually the native element.

Executing something like this successfully changes the background color (for testing purposes only - not for actual use):

this.component.style.backgroundColor = 'red';

Although I achieved the desired outcome with this method, I still have a few questions to deepen my understanding.

  1. Is #content considered the native element rather than the ElementRef?
  2. Is this the correct way in Angular to pass a reference variable to another component?

If you believe there is a more appropriate approach or have a better example to provide, please share some valid insights.

Answer №1

ngOnInit() may not be the right time to access certain elements. ngAfterViewInit() could be a better choice:

ngAfterViewInit() {
  console.log(this.component); // this will display the html element in the console
  console.log(this.component.nativeElement); // this will show as undefined
}

Could #content refer to the actual element instead of the ElementRef ?

If #content is used on a regular element, it represents the nativeElement.
If the element contains a component or directive, you will receive the instance of that component or directive.

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

Encountering an issue in Angular 8 flex-layout 8: Unable to export member ɵNgClassImpl

I encountered an issue while trying to install flex-layout 8.0.0-beta.26 in my Angular 8 project. The error I received during the build process is as follows: ERROR in node_modules/@angular/flex-layout/extended/typings/class/class.d.ts(9,19): error TS2305 ...

The angular-CLI does not support the use of content delivery networks (CDNs) within the .angular-cli.json

Is there a way to make angular-cli recognize when we add any deployed URLs for styles or scripts using CDN? Currently, adding them to index.html works but adding to .angular-cli.json has no effect. Any workaround available? ...

Is there a way to assign a specific item in *ngFor to a reference variable?

Looking for help with this piece of code I have: <ng-container *ngFor="let item of results; let i = index"> <ion-item #triggerElement lines="none"> I want to set the reference #triggerElement to the item with the index of 3. Any idea ...

What is the best way to attach events to buttons using typescript?

Where should I attach events to buttons, input fields, etc.? I want to keep as much JS/jQuery separate from my view as possible. Currently, this is how I approach it: In my view: @Scripts.Render("~/Scripts/Application/Currency/CurrencyExchangeRateCreate ...

When running the command "ng build --prod" in Angular 5, you may encounter an error stating

My project runs smoothly when I use ng serve locally. However, when I run ng b -prod, I encounter the following error: ERROR in app\logged-in\content\routing\routing.component.ts(9,16): Error during template compile of 'Routing ...

Using Angular 2: Exploring the power of observables for broadcasting events during a forEach loop

Upon testing the service within a forEach loop, I noticed that the parameter I passed to the service ended up being the last one in the iteration. I initially suspected that the issue was due to closures, so I attempted using an anonymous function to add ...

Error in StoryBook addon-docs: "No props discovered for this particular component" when utilizing TypeScript

Encountering an issue with a TypeScript and StoryBook project: The table displaying component properties is not generated nor visible in the StoryBook "Docs" tab on a TypeScript-based project setup. Instead of the expected table, a message saying "No pro ...

Component declaration in Typescript is being rejected due to the union type not being accepted

In my current project, I'm working on a component that should accept either an onClick or a to prop. const StickyButton: React.FC< ({ onClick: MouseEventHandler } | { to: string }) & { buttonComponent?: ({ onClick: MouseEventHandler }) =& ...

How do you implement an asynchronous validator for template-driven forms in Angular 2?

I have created a custom directive for my asynchronous validator: @Directive({ selector: '[validatorUsername]', providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: ValidatorUsernameDirective, multi: true }] }) export class ValidatorUsern ...

The union type cannot function effectively in a closed-off environment

Here is the code snippet I am working with: if (event.hasOwnProperty('body')) { Context.request = JSON.parse(event.body) as T; } else { Context.request = event; } The variable event is defined as follows: private static event: aws.IGateway ...

Angular 8 Issue: Absence of _body and Headers in Response

Our back-end code is written in C# within the .NET environment, targeting the 4.6.1 framework. Recently, our front-end was upgraded from Angular 4 to Angular 8. During this upgrade, webpack transitioned from version 2.3 to version 4.41 and typescript from ...

Displaying Data in a Tree Structure Using JSON

I am currently working on an Angular project which includes a nested JSON file structured as follows: I would like to import this JSON data from the file and create a treeview populated with its contents. How can I achieve this? { "?xml": { ...

Looking for a regular expression to verify if the URL inputted is valid in TypeScript

After conducting thorough research, I discovered that none of the suggested URLs met my criteria, prompting me to raise a new query. Here are my specific requirements: * The URL may or may not include 'http' or 'https' * The URL can co ...

Error in Node: JSON parse failure due to invalid token "'<'" and ""<!DOCTYPE ""

Every time I attempt to run node commands or create a new Angular project, I encounter the following error. Node version 20.11.0 NPM version 10.2.4 ...

The interactive Material UI Radio buttons are not responding to click events due to dynamic generation

Click here to see the demo in action: https://codesandbox.io/s/material-demo-9fwlz I expected this code to produce checkable radio elements, but it doesn't seem to be working correctly. Can anyone identify what might be causing the issue? This code s ...

Navigate to the previous page

What is the best way to navigate back to the last page in Angular 2? Can it be done like this? this._router.navigate(LASTPAGE); For instance, if page C includes a Go Back button, From Page A to Page C, clicking it will take you back to Page A. Fro ...

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...