The program encountered an error with code TS2339, indicating that the property "name" cannot be found on the type "never"

app.component.html I'm attempting to display the response data from my Firebase project using *ngFor.

<div class="row">
        <div class="col-md-3">
            <h4 class="text-warning">All Employee Data</h4>
            <div class="card" *ngFor="let item of employee">
                <div class="card-body">
                    <div class="card-title">
                        Name: {{item.name}} // error-Property 'name' does not exist on type 'never'.
                    </div>
                    <div class="card-subtitle">
                        Age: {{item.age}} // error-Property 'name' does not exist on type 'never'.
                    </div>
                    <div class="card-text">
                        Address: {{item.address}} // same error here also
                    </div>
                </div>
            </div>
        </div>
    </div>

app.component.ts In this file, I am fetching data from my Firebase project.

export class AppComponent implements OnInit {
  title = 'App';

 constructor( private _crudService:CrudService) {}

     employee:[] = [];
     employeeName: string = '';
     employeeAge: number | undefined;
     employeeAddress: string = '';
     message: string ='';

 ngOnInit(){
  this._crudService.getAllEmployee().subscribe((data:any) =>{
    this.employee = data.map((e:any) =>{   // I am storing the response in an empty array  
      return{
        id: e.payload.doc.id,
        name: e.payload.doc.data()['name'],
        age: e.payload.doc.data()['age'],
        address: e.payload.doc.data()['address']

      }
    });
    console.log(this.employee);
  }); 
 }

crud.service.ts This file contains the request being sent to retrieve Employee Data.

getAllEmployee(){
    return this.fireservice.collection('Employee').snapshotChanges();
  }

Answer №1

Method 1: Using Safe Navigation Operator

When the component is first rendered, the array employee may be empty. To avoid errors, you can utilize the safe navigation operator ?. to check if a property exists before attempting to display it.

<div class="card-title">
  Name: {{ item?.name }}
</div>
<div class="card-subtitle">
  Age: {{ item?.age }}
</div>
<div class="card-text">
  Address: {{ item?.address }}
</div>

Method 2: Leveraging the async Pipe

If the variable this.employee is solely used for template rendering, you can opt to skip the subscription in the controller and instead employ the async pipe within the template.

Controller

import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';

export class AppComponent implements OnInit {
  title = 'App';
  employees$: Observable<Array<any>>;
  employeeName: string = '';
  employeeAge: number | undefined;
  employeeAddress: string = '';
  message: string = '';

  constructor(private _crudService: CrudService) {}

  ngOnInit() {
    this.employees$ = this._crudService.getAllEmployee().pipe(
      map((e: any) => ({
        id: e.payload.doc.id,
        name: e.payload.doc.data()['name'],
        age: e.payload.doc.data()['age'],
        address: e.payload.doc.data()['address']
      })),
      tap(console.log)
    );
  }
}

Template

<ng-container *ngIf="(employees$ | async) as employees">
  <div class="row">
    <div class="col-md-3">
      <h4 class="text-warning">All Employee Data</h4>
      <div class="card" *ngFor="let item of employees">
        <div class="card-body">
          <div class="card-title">
            Name: {{ item['name'] }}     
          </div>
          <div class="card-subtitle">
            Age: {{ item['age'] }}
          </div>
          <div class="card-text">
            Address: {{ item['address'] }}
          </div>
        </div>
      </div>
    </div>
  </div>
</ng-container>

Answer №2

One way to handle the data is by employing JSON.parse(JSON.stringify(data)) prior to

this.employee = data.map((e:any) =>{   // saving results in an empty array here  

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

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Enhancing Typescript Arrow Function Parameters using Decorators

Can decorators be used on parameters within an arrow function at this time? For instance: const func: Function = (@Decorator param: any) => { ... } or class SomeClass { public classProp: Function = (@Decorator param: any) => { ... } } Neither W ...

Is condition checking taken into consideration by Typescript?

I keep encountering this strange TypeScript compile warning that just won't go away, even though I believe it shouldn't be there in the first place... Here are the interfaces I'm working with: interface Props { tasks: TaskType[] } inter ...

Adding services to an Angular class instance for dependency injection

When attempting to utilize an instance of a class within a static property of another class, I encountered the following issue: class MyHelper { private authService: AuthService; constructor() { this.authService = inject(AuthService); this ...

Searching Firestore database using parameters in the URL

I am striving to retrieve plants that have a folderId with a value based on the parameters from useRouter. Although there are no errors, no data is being returned, and there are indeed plants with folderId in the "PlantsData" collection. Here is the code ...

Instructions on how to present a list of employee information according to the user's gender preference using a selection of three radio buttons

I have developed a view that displays a table of employees, using a json array to store their details in the component. Additionally, I have implemented 3 radio buttons: all, male, and female. My goal is to have the table show all employees when "all" is ...

Angular Input Validation for Multiple Entries

Has anyone else tried creating a validator that checks for duplicate email addresses in a list? I am attempting to implement this feature where the validator takes an email address from a text input and compares it against a list of emails. The code snipp ...

An example of using the index as an attribute within the same tag in Angular 2 *ng

Currently, I am in the process of creating a bootstrap carousel. To accomplish this, I have utilized *ngFor to add elements and carousel-indicators (small circles that show the current position). <li data-target="#myCarousel" *ngFor="#item of items; #i ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

Communicating Progress Updates from C# to Angular 6 Using HttpPost

I'm building an Angular 6 application with a progress bar that displays the rendering and downloading progress of a PDF file as a percentage. Here's my Post call: renderReport(renderObjectId: number): Observable<HttpEvent<Blob>> { ...

What sets template-driven and reactive forms apart in practice?

Exploring the Angular2 new Forms API has revealed two distinct approaches to forms: Template driven and reactive (model-driven) forms. I am curious about the real-world differences between these two methods, beyond just syntax. Which approach is more adva ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

The ng-bootstrap datepicker does not allow setting a default date prior to selection

I have implemented the ng-bootstrap date picker in my project and I am facing an issue with setting a default date for the input field before selecting a date from the datepicker itself. <input type="text" id="datepicker{{i}}" class="form-control" form ...

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

What is the best arrangement of folders for an enterprise Angular 16 project that ensures both scalability and maintainability over an extended period of time?

Embarking on a significant Angular project with multiple features and modules ahead of me, I find myself in a quandary over the best folder structure to ensure scalability and easy maintenance in the long run. This project will encompass three modules, wi ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

The ng build command encounters a failure (module cannot be found) when running in a docker environment on Ubuntu, while it successfully runs

I'm facing an issue that I can't quite pinpoint whether it's related to docker, Ubuntu, or node/npm. Here are all the details I have: Although there are known causes for this module error, none of them explain why it works on various Window ...

Exploring the functionality of this TypeScript code: What's the distinction between { [key: string]: string }[] and { prop1: string, prop2: string }[]

Below is the code I am currently working with: get tags(): { [key: string]: string }[] { let tags: { [key: string]: string }[] = []; if(this.tags) { Object.keys(this.tags).forEach(x => { tags.push({ prop1: this.tags[x], prop2: g ...