There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle().

Encountering this exception error:

ERROR TypeError: _v.context.$implicit.toggle is not a function

Appreciate any help or insights.

tree-view.component.ts

export class TreeViewComponent implements OnInit {  
  constructor() { }
  ngOnInit() {}     
  @Input() directories: Directory[];
}

tree-view.component.html

<ul>
  <li *ngFor="let dir of directories">
    <label (click)="dir.toggle()"> {{ dir.title }}</label>
    <div *ngIf="dir.expanded">
      <tree-view [locations]="dir.children"></tree-view>
    </div>
  </li>
</ul>

Directory.ts

 export class Directory{

      title: string;
      children: Directory[]
      expanded = true;
      checked = false;

  constructor() {

  }

  toggle() {
    this.expanded = !this.expanded;
  }

  getIcon() {
    if (this.expanded) {
      return '-';
    }
    return '+';
  }
}

Answer №1

Following yurzui's suggestion, if you are simply inputting your data without using class instances, then the toggle method will not be available. To have an array with instances of your Directory class, include the properties in the constructor and create instances of your objects when retrieving data from the API. Here is a condensed version:

export class Directory {
  title: string;
  expanded: boolean;

  constructor(title: string, expanded: boolean) {
    this.title = title;
    this.expanded = expanded; 
  }
}

Update your API call as follows:

return this.httpClient.get<Directory[]>('url')
  .map(res => res.map(x => new Directory(x.title, x.expanded)))

You can now access the toggle method.

Check out the StackBlitz example

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

Steps for altering the primary color in PrimeNG__Changing the primary color

What is the most effective way to modify the default primary color for primeNG (saga-blue theme)? Altering --primary-color does not have the desired effect, as elements in node_modules/..../theme.css are styled using the main color hex rather than '-- ...

Transform JSON structure (Group data)

Here is the JSON object I am working with: [{ "name" : "cat", "value" : 17, "group" : "animal", }, { "name" : "dog", "value" : 6, "group" : "animal", }, { "name" : "snak", "value" : 2, "group" : "animal", }, { "na ...

Encountering the 'Default setting for timestampsInSnapshots now set to true' error in Firestore console

Encountering a Firestore error in the console while using Angular. @firebase/firestore: Firestore (5.8.3): The timestampsInSnapshots setting now defaults to true and does not require explicit setting. It is advised to remove it from firestore.settings( ...

Errors in the Latest Release of Angular2 and Visual Studio 2015

After taking a stroll through the Angular 2 Tour of Heroes sample application with the latest Angular 2 version, I decided to host it within a Visual Studio 2015 Empty Web application. Following the Angular sample closely means that I'm not incorporat ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Issue with Sending Messages using SignalR in .NET and Angular

I am attempting to make a simple SignalR example work, following Microsoft's tutorial and using the Weatherforecast .NET/Angular SPA from Visual Studio as a starting point for a project I plan to integrate SignalR with in the future. You can find the ...

Pass information to a PHP file using JavaScript when the form is submitted

Essentially, I am looking to extract values from various inputs and spans using JavaScript when the submit input is clicked. These values will then be sent to PHP using $post in order to ultimately send them via email. Previously, I tested replacing all of ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

Access information through the restful api using the angularjs service $resource

I am attempting to utilize the $resource service with the surveygizmo API. Here is my code: HTML : <div ng-app="Survey"> <body> <div ng-controller="SurveyCtrl"> {{survey.data.title}} </div> </body> </div> My scr ...

Trigger a Jquery sound when an HTML result is found and displayed

I am using a Jqgrid to display a table. Within the "return" column, along with other data, there is a span element like the following: <span class="return" id="ret0>4.25%</span> My webpage contains multiple instances of these spans: < ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

Having trouble with the JSON format within the 'operations' field in the formData of your Next.js application?

I encountered a mutation that looks like this- mutation signUp($avatar: Upload!) { signUp( avatar: $avatar input: { name: "Siam Ahnaf" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Having difficulty populating a selection box through an ajax request in Django

I am facing an issue with creating cascading select boxes in my project (backend Django), although I believe most of the backend work has been completed. The JavaScript code I'm using is adapted from a solution found on a stackoverflow post. $(docume ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

Trouble Navigating the DOM

Can you assist me in choosing the correct option c? Below is the provided HTML code: <div id="a"> <div id="b"></div> <div id="app7019261521_the_coin_9996544" style="left: 176px; top: 448px;"> <a href="d.com" oncl ...

Set markers at specific locations like "breadcrumbs" and generate a route using Google Maps API v3.exp

I'm developing a new iOS application for scouting out locations while on the move. I want users to be able to mark each location by simply clicking a button, which will drop a marker based on their current location. The ultimate goal is to connect all ...

Tips for preventing a page from automatically scrolling to the top after submitting a form

Recently, I set up a form where users can input values. The form is set to submit either on change or when the user hits enter, depending on which value they want to update. However, after the values are submitted, the page automatically jumps back to the ...

refresh the localstorage array using vanilla JavaScript

I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array: ["96", "281", "287", "415", "650", "661", & ...

What are the reasons behind the jQuery file upload failing to work after the initial upload?

I am currently utilizing the jQuery File Upload plugin. To achieve this, I have hidden the file input and set it to activate upon clicking a separate button. You can view an example of this setup on this fiddle. Here is the HTML code snippet: <div> ...