Click event for a tree component in Angular 2

How can I trigger a node click event in an Angular tree component?

import { TREE_ACTIONS, KEYS, IActionMapping } from 'angular2-tree-component';

const actionMapping:IActionMapping = {
  mouse: {
    click: TREE_ACTIONS.TOGGLE_SELECTED_MULTI
  },
  keys: {
    [KEYS.ENTER]: (tree, node, $event) => alert(`Displaying node name: ${node.data.name}`)
  }  
}

Answer №1

An important point to emphasize here is how the options object is assigned to the tree object. This step is carried out within the template, as shown below:

<tree-root [nodes]="nodes" [options]="treeOptions"></tree-root>

Subsequently, in the component.ts file, ensure that you link it as shown below:

treeOptions = { actionMapping: this.actionMapping }

It took a bit of time to figure this out, especially since the documentation lacks clarity on this particular aspect.

Answer №2

If you want to bind various events, you can follow the instructions provided in this example.

For instance:

<tree-root [nodes]="nodes"
    (activate)="callMethodA($event)"
    (deactivate)="callMethodB($event)">
</tree-root>

Answer №3

Here's a simple example of handling a click event:

import { TreeNode, TreeModel, TREE_ACTIONS, KEYS, IActionMapping, ITreeOptions } from 'angular-tree-component';


const actionMapping:IActionMapping = {
mouse: {
click: (tree, node, $event) => {
  $event.shiftKey
    ? TREE_ACTIONS.TOGGLE_SELECTED_MULTI(tree, node, $event)
    : TREE_ACTIONS.TOGGLE_SELECTED(tree, node, $event)
}
   }
 };

@Component({
      selector: 'category',
      template: `  <div class="d-inline-block">
                  <tree-root #tree [nodes]="categories">
                    <ng-template #treeNodeTemplate let-node let-index="index">
                        <span>{{ node.data.name }}</span>
                        <button (click)="addNode(tree)">add</button>
                    </ng-template>
                 </tree-root>
                </div>`,
      styles : [styles]
})

export class Category implements OnInit {
public categories :any;
  addNode(tree) {
      this.categories[0].children.push({
      name: 'a new child'
  });
   tree.treeModel.update();
}

Answer №4

Whenever a node is clicked, it becomes selected and triggers the (activate) event. You can define a method for this event by passing $event as a prop. This way, you can access the clicked node by implementing that method in your component.ts file, for example, $event.node.

component.html file

<tree-root [nodes]="nodes" [options]="options" (activate)="onClick($event)"></tree-root>

component.ts file

public onClick(event) {
  console.log('>> onClick', event.node.data);
}

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

Setting default values on DTO in NestJS can be done by using the DefaultValue decorator provided

import { IsString, IsNumber, IsOptional, IsUUID, Min, Max } from 'class-validator'; import { Transform } from 'class-transformer'; export class QueryCollateralTypeDto { @Transform(({ value }) => parseInt(value)) @IsNumber() @I ...

Typescript's identification of a dispute between RequireJS and NodeJS definitions

I obtained the Typescript RequireJS definition from Definitely Typed. It includes an ambient declaration of Require that clashes with the NodeJs command "require". See below for the declaration and the error message: Declaration: declare var require: Req ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

What is the best way to change a number into a byte string using TypeScript?

If I have a number represented by 3 bytes in hexadecimal form as 0x303132, how can I transform this number into a string of three characters with the same value - '012' - where each character represents the ASCII value of the corresponding byte? ...

Encountering "No provider for TemplateRef" error in Angular 15+ when using a structural directive as the

Since the release of Angular version 15, it is now possible to bind standalone directives to component and directive decorators. Is there a way to utilize structural directives (with injected TemplateRef) as a hostDirective? This feature would be extremely ...

What is the best approach for unit testing with a subscribe in Angular 5?

import { Component, Input, OnInit } from '@angular/core'; import {DataplansDetails} from '../../models/dataplans-details'; import * as _ from "lodash"; @Component({ selector: 'jsonform', templateUrl: './jsonform.comp ...

Creating nested Angular form groups is essential for organizing form fields in a hierarchical structure that reflects

Imagine having the following structure for a formGroup: userGroup = { name, surname, address: { firstLine, secondLine } } This leads to creating HTML code similar to this: <form [formGroup]="userGroup"> <input formCon ...

I recently used the ng new ang-routing command to generate a fresh Angular project in my directory, but encountered an error while doing so

npm ERR! syscall read npm ERR! errno ECONNRESET npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/@angular-devkit%2fbuild-angular: read ECONNRESET npm ERR! network This issue is likely caused by connectivity problems. ...

Accessing the menu

There are two main headings in my menu: Administration and Market https://i.sstatic.net/JbePq.png When I click on the Administration heading, submenus for Portfolio and Corporate Action are displayed https://i.sstatic.net/oyabv.png The issue I am facin ...

"Error encountered: 'Callable function cannot be invoked on Mongoose model

In my Nest JS service, the code structure is as follows: import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { Collection } from './inter ...

The type does not meet the requirements set by the class it is inheriting from

Currently, I am in the process of working on a WebSocket Secure (WSS) server utilizing the Node ws library which can be found here. More specifically, I am following the approach outlined in this particular question, although its relevance is yet to be det ...

Prevent assignment of properties from a subclass

Let's consider the scenario below: interface Base { a: string; } interface Derived extends Base { b: string; } const x: Derived = { a: "a", b: "b", }; How can we configure the linter and/or compiler to detect any issues ...

Tips for incorporating Material UI Icon v1.0.0-beta.36 into a .tsx component

Currently utilizing material-ui-icons v1.0.0-beta.36. I am endeavoring to incorporate a Search icon within a .tsx component. .tsx component: import React, { Component, ReactElement } from 'react' import Search from 'material-ui-icons/Sear ...

Is it possible to create a prototype function within an interface that can group items in an array by a specific property, resulting in an array of objects containing a key and corresponding array of values?

I've been working on this code snippet and I'm trying to figure out how to make it work: Array<T>.groupBy<KeyType> (property): {key: KeyType, array: Array<T> }[]; The code looks like this: type ArrayByParameter<T, KeyType = ...

The Jest worker has run into 4 child process errors, surpassing the maximum retry threshold

I am a newcomer to Vue and Jest testing, and I keep encountering this error when running a specific test. While I understand that this is a common issue, I am struggling to pinpoint the exact cause of the problem. Here is the error message: Test suite fa ...

Having trouble with Angular 2 Routing and loading components?

I am facing an issue with Angular 2 where it is searching for my component in app/app/aboutus.component, but I cannot pinpoint the source of the problem. Here is my app.component.ts code: import { Component } from '@angular/core'; import { ROUT ...

Encountered a problem with regular expressions in Angular 2 - a Module parse error due to an octal literal in strict mode

Greetings, I have encountered an issue with a regular expression in my environment.ts file. export const environment = { passwordPolicy: "^(?!.*(.)\1\1)(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}.*$" }; Unfortunately, whe ...

Customizable JSX Attributes for Your TSX/JSX Application

Currently, I am in the process of converting my React project from JavaScript to TypeScript. One challenge I encountered is that TSX React assumes all properties defined in a functional component are mandatory props. // ComponentA.tsx class ComponentA ext ...

Guide to importing an npm module with a Typescript main file in a Typescript project

I'm struggling to figure out the correct method for importing a Typescript npm module. Here is my current approach: module package.json { "name": "my-module", "main": "src/myModule.ts" } module src/myModule.ts export module MyModule { // Co ...

How to Toggle Visibility of Angular2 Material Drop Down Menu?

My Code <mat-form-field class="button-spacing"> <mat-select placeholder="select" [(ngModel)]="dropDownOne"> <mat-option *ngFor="let first of test1" [value]="first"> {{ first }} </mat-option> </mat-select> </mat-fo ...