The component does not have a property named 'hero'

I'm currently working on the "Tour of Heroes" tutorial, but I've encountered an error that I can't seem to resolve.

src/app/app.component.html:3:25 - error TS2339: Property 'hero' does not exist on type 'AppComponent'.

3 <div><span>Id: </span>{{hero.id}}</div>
                          ~~~~

  src/app/app.component.ts:7:16
    7   templateUrl: './app.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component AppComponent.

Below is the code for app.component.html:

<h1>{{title}}</h1>
<div><span>Id: </span>{{hero.id}}</div>
<div><span>Name: </span>{{hero.name}}</div>

And here is the code for heroes.component.ts:

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
   hero: Hero = {
     id: 1,
     name: 'Windstorm',
   }



  constructor() { }

  ngOnInit(): void {
  }

}

Answer №1

To properly utilize the property "hero" from the HeroComponent within the context of the app.component, it is essential to ensure that the interpolation takes place within the AppComponent. If it is necessary to declare the hero property inside the HeroComponent and use it in the AppComponent, effective communication between components is crucial. This can be achieved through mechanisms like @Input/@Output decorators or employing a Service

Answer №2

Providing assistance for those facing challenges with the tutorial.

If you are attempting to import a component into another and it's not working as expected, there may be an issue with the tutorial. In my experience, I did not have an app.module.ts file when I started a new project using Angular CLI 17.0.5. This means that the instructions on magically importing the HeroesComponent may not apply in your case. In any event, to include a component within another, you have two options: either the component stands alone or you need to use ngModules, which is covered later in the tutorial.

To import your Heroes Component without using ngModules, you must add this line in the @Component section of your app.component.ts file:

standalone: true,

Additionally, in the app.component.ts file, make sure to import your HeroesComponent at the top like so:

import { HeroesComponent } from './heroes/heroes.component';

Further down in your @Component declaration, it should resemble this structure:

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, HeroesComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})

Note: The latest version of Angular CLI now supports standalone components instead of ng modules. However, the Heroes tutorial available as of December 2023 is still designed for an angular app utilizing ngmodules. For more information, refer to: https://github.com/angular/angular/issues/52751

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

Is it possible to switch between mat-checkbox and mat-radio-button within an Angular reactive form?

As I develop a quiz application, I face the challenge of dynamically switching between mat-checkbox and mat-radio-button based on the number of answers for each question. For instance, Question #1 is a single choice question and utilizes mat-radio-button, ...

Collaborate on code for a cross-platform mobile application and a traditional desktop web application

I have a vision to create a cutting-edge app that can be utilized as both a hybrid mobile application and a desktop web application. For the most part, the logic and user interface will remain consistent across both versions. However, there are a few key ...

Can the Node DNS module be incorporated into Angular code?

I am facing a requirement where I must perform a DNS lookup from client-side code built in Angular. Is it feasible to utilize the DNS module from https://nodejs.org/api/dns.html in Angular? ...

Observable emitting individual characters instead of the entire string in an optional parameter of an activated route

Within an Angular component, I have a method with the following content: this.route.paramMap.pipe( switchMap((params: ParamMap) => { let fooValue = params.get('selectedid'); console.log("inside switch map with value as " + ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

Angular is declining to implement the style originating from the specified URL

I'm currently working on an Angular application and attempting to lazy load a module called ProjectsModule. The projects component is displayed without any issues, but when I navigate to a specific project like /projects/1, everything looks fine until ...

Utilizing Angular Universal on an existing Express server for enhanced functionality

I have an Express server set up to host my Angular application as static content, along with other functionalities. However, I now want to integrate Server-side Rendering using Angular Universal, which requires a separate Express server just for serving th ...

Angular Containerization with Service Fabric

Currently grappling with the concept of containerized Angular applications pushed to Service Fabric. By following this particular guide, I successfully managed to pull an image, run it locally, and have now successfully pushed it to my Service Fabric Conta ...

Can dynamic placeholders be implemented for Angular 6 material inputs?

Currently, I am attempting to dynamically adjust the placeholder of a Material input field based on calculations that are taking place in the background. These calculations derive from the user's responses to other questions on the form. I have exper ...

How can you test the RTK Listener middleware?

Exciting news - I am experimenting with the new listener middleware from redux-toolkit in combination with React and Typescript! I have achieved some great results so far, but now I am eager to take it to the next level by implementing tests for my logic. ...

Tips for creating a versatile function in TypeScript that accepts either a single value or an array of values for two parameters

I'm currently working on a task to develop a versatile function that accepts a parameter called hashMapName, another parameter called 'keys' which can be either a string or an array of strings, and a callback function that will return either ...

The positioning of the legend in ngx-charts seems to be off

Greetings to all developers, I have been utilizing ngx-charts for my charting needs, and overall, everything has been working well. However, I am encountering an issue when attempting to change the position of the legend to below the chart. It seems to ex ...

What is a secure method for detecting variances between two objects in TypeScript?

I have two objects with similar properties. I want to compare the values of each property in both objects and find the differences. The following code is functional but generates TypeScript errors: export type Item = { name?: string; age?: number; l ...

Unable to make a reference to this in TypeScript

In my Angular2 application, I have a file upload feature that sends files as byte arrays to a web service. To create the byte array, I am using a FileReader with an onload event. However, I am encountering an issue where I cannot reference my uploadService ...

Testing for target instanceof window.Window in jest involves writing a test case using the expect keyword

I am currently working on a function in TypeScript that handles scrolling. Here is the code snippet with type definitions for reference... function scroll(target: HTMLElement, {posX, posY}: ScrollPosition): void { if (target instanceof window.Window) ...

Choosing between direct imports and package imports in JavaScript

Question: Seeking feedback on the preferred import/export/usage system in TypeScript. While direct imports (#1) are common, which approach is considered best practice in well-established production codebases? Context: Having worked on large-scale projects ...

Issue with NgRx Testing: Callback in subscribe method fails to update during testing

I am currently working on testing a component that is responsible for editing shopping list items. Upon first loading, the component receives state values through store.select, which are: editedIngredient: null, editedIngredientIndex: -1 Based on these ...

Handling errors with Observable.catch() in RxJs

I am struggling to grasp the concepts of RxJS and error handling, especially within an Angular (4+) environment. The transition to RxJS for basic HTTP requests has presented me with unexpected challenges that seem overly complex. Here is a snippet of my c ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

The current error message is: "ReferenceError: spyOnProperty is not defined

it('needs to be able to update treatment instructions in the user interface', async(() => { const spy = spyOnProperty(appService.treatmentInstruction, 'next', 'get').and.returnValue(treatmentInst); component ...