"encountering a TypeScript error stating 'context.$implicit' is not a

I am currently working on a class setup that includes:

import { ClassAsset } from './class-asset';

export class Class {
    ClassId:string;
    ClassName:string;
    Assets:ClassAsset[];

    GetAssetsString():string{
        var str:string;
        this.Assets.forEach(a=>{str+=a.AssetName;});

        return str;
    }

Attached is the Angular view code snippet

<tr *ngFor="let cls of classList">
        <td>{{cls.className}}</td>
        <td>{{cls.GetAssetsString()}}</td>
      </tr>

The structure of my Component is as follows:

export class ClassesComponent implements OnInit {
  private _client:HttpClient;
  public classList:Class[]=[];

  constructor(client:HttpClient,private route:Router,private datasource:DataService) {
    this._client=client;
   }

  ngOnInit() {
    this.getClasses();
  }

  getClasses()
  {
    this.datasource.getClassList().subscribe((resp:Class[])=>{
      console.log(resp);
      this.classList=resp;}
      );
  }
}

Unfortunately, I encountered the error message below:

TypeError: _v.context.$implicit.GetAssetsString is not a function

Can someone please assist me in identifying what went wrong? (I am still in the learning process with TypeScript...)

Answer №1

When you receive a response from the server and try to convert it into your Class object, it may not work if the object only contains data without any functions. This could be why the GetAssetsString function is not accessible in your code.

To resolve this issue, you can define a constructor within your Class object like so:

export class Class {
    ClassId:string;
    ClassName:string;
    Assets:ClassAsset[];
    
    constructor(obj?:any){
      this.ClassId= obj && obj.ClassId || '';
      this.ClassName= obj && obj.ClassName || '';
      this.Assets = obj && obj.Assets || [];
    }
    
    GetAssetsString():string{
        var str:string;
        this.Assets.forEach(a=>{
            str+=a.AssetName;
        });
        
        return str;
    }
}

Then, update your getClasses method like this:

          getClasses()
          {
            this.datasource.getClassList().pipe(map(response =>
            response.json())).subscribe(x=>{
              this.classList= x.map(x1=>new Class(x1));
              });
          }

Hope that helps!

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

Should compile time errors be triggered by generic function constraints?

Surprisingly, the following code does not throw a compile time error as expected. interface Service { } abstract class TestService implements Service { } class TestServiceImpl extends TestService { } class Blah { } function getService<T extends S ...

Inform the Angular2 Component regarding the creation of DOM elements that are placed outside of the

The Challenge In my Angular2 project, I am using Swiper carousel and building it with Webpack. However, Angular2 adds random attributes like _ngcontent-pmm-6 to all elements in a component. Swiper generates pagination elements dynamically, outside of Ang ...

Hide the tab in React Native's bottom tab navigation when on the current screen within the navigator

Currently, I am delving into learning react native. My project consists of 4 screens, yet I only require 3 buttons on my tab navigator. The objective is to hide or eliminate the active screen's tab from being accessible. Specifically, when on the home ...

Guide on pre-selecting an option in a select control using Angular

I need some assistance with the following: My select control is defined as shown below, and I populate its options with strings from an array of strings in my component named tools.Attributes.Serials. Everything is functioning correctly: <select class= ...

The optional chaining feature seems to be malfunctioning as it is unable to access the property '0' of an undefined value

Why isn't optional chaining working in this scenario? .html {{userItemModel?.item?.priceList[0]?.sellerUrl}} An error is displayed: TypeError: Cannot read property '0' of undefined "@angular/core": "~10.1.1", "t ...

Displaying dates with suffixes (st, rd, and th) in expression using Angular 2/4/5

How can we appropriately add suffixes (st, rd, and th) to dates in Angular 2/4/5 and beyond using the "Angular way"? For instance, displaying dates like February 25th, March 1st, April 2nd within an Angular expression {{item | date: ???}} The documentati ...

The sanitizer variable becomes null when accessed outside of the NgOnInit function in Angular using TypeScript

At first, I added DomSanitizer to the component: import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser'; Next, a class was created and included in the constructor: export class BlocklyComponent implements OnInit { primar ...

Unable to switch the icon for expanding/collapsing the current node

How can I change the icon of a specific tree node when it is expanded or collapsed? Currently, my code changes all icons in the tree instead of just the one I clicked on. Here's my current code: HTML file <div class="container sidenav-tree"> ...

When the @Input() contains an unaltered boolean value, it does not initiate change detection

I have developed an Angular application featuring a popup component. The visibility of the popups can be controlled both from its parent and the popup itself. app.component.ts import { Component } from '@angular/core'; @Component({ selector: ...

Discover how TypeScript's strictNullChecks feature can help you identify null values with ease in your functions

Since Javascript often requires me to check if a value is `!= null && != ''`, I decided to create a function that checks for empty values: const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => { return variable == null | ...

Navigating through pop-ups in Chrome: A guide to using Protractor

Currently, I am utilizing Protractor and am faced with the challenge of handling a pop-up from Chrome. My goal is to successfully click on the button labeled "Open magnet URI". For a visual representation of the issue, refer to the following image: picture ...

Angular 7: Resetting multiple dynamically generated checkboxes back to their original state with the click of a button

I have created a child component that contains 3 checkboxes, generated dynamically using ngFor, along with Apply and Cancel buttons. In the parent template, I include the selector tag for the child component. The parent component accesses this child compo ...

What is the best way to simplify passing repeated children properties while ensuring non-optional types are maintained?

One of my components is being used multiple times consecutively with some properties being repeated and some being unique: interface InsideComponentProps { repeatedThing: string; uniqueThing: string; } const InsideComponent: React.SFC<InsideCo ...

Enhance the step implementation in Cucumber-js

Background In my TypeScript project, I am utilizing https://github.com/cucumber/cucumber-js. The code snippet below showcases a typical cucumber implementation: import { Given, Then, When } from 'cucumber' Given(`Page is up and run ...

The generation of the .prisma folder in the Node process is causing a file lock, which is hindering the progress of future

Node: 20.11.1 Azure Pipeline: Ubuntu 22.04.4 LTS Prisma: 5.10.2 I am currently utilizing an Azure pipeline to run a typescript-based ExpressJS application. Displayed below is the contents of my package.json: { "name": "...", & ...

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

The 'co.Number' function is not recognized as a valid function due to a

I'm attempting to perform string multiplication using Angular. <h5>{{Number(someString) * Number(someOtherString)}}</h5> Unfortunately, I encountered this error: ERROR TypeError: co.Number is not a function Is there a way to multiply ...

Tips for setting ngModel and name attributes in an angular test for a custom component

Just getting started with angular. I recently developed a custom component that implements the ControlValueAccessor to allow developers to easily access its value. Here's an example of how it can be used: <app-date [label]="'Date 2&apos ...

The fix for the unresponsive fixed container in Angular 2 Material

I've encountered an issue with CSS and Angular 2 material. Any element with a fixed position doesn't behave as expected inside an md-sidenav-container. However, when it is placed outside the container, it works perfectly. I have created a Plunker ...

Is it possible to execute methods in the initialization phase using Express Route?

My express app has a simple structure, with the main file app.ts configured like this import * as express from "express"; const application: express.Application = express(); application.get("/", function( request: express.Request, ...