Simple BUTTON trick with Angular.JS

I got stuck while programming our Access Control System. I did not want to allow for the deletion of a Module if it had any Child Modules. If this was done, the Child Modules would become Parent less and I would not be able to construct the Menu.

The starting screen displayed looks as provided below.


The Modules in the system are displayed in a Tree View. The user can edit or delete a module using this UI.

The user can edit any of the Module Details except for the Root Module details. This is because the Root Module details are not stored on the database.

However, the User should be able to delete only leaf level Modules.

Now, I store the data for the modules in the following class.

export class MenuTree {
      id: string;
      name: string;</div>
      children: MenuTree[];</div>

Due to this storage, it is possible for me to know whether a node has child nodes or not. This is done by checking whether the node.children is null or if node.children has any elements in it. If node.children has any entries, then the node is a parent node and thus has children.

Now, I want Delete button to be enabled only if (node.children is null) or (node.children.length <= 0).

Now coming to the Angular part.

I place a button in the html for the Delete operation. The button object has a Javascript property called disabled. However, this property cannot be changed dynamically. Fortunately, Angular comes to the rescue with the *ngIf directive.

What I did was to define 2 buttons instead of one for the Delete operation. One button was enabled and one was disabled. I display the appropriate button based on whether the node can be deleted or not.

The HTML code is as follows:

          <div *ngIf="canDelete">
              <button mat-raised-button color="warn" type="button" (click)="onDelete(selectedModuleCode)">Delete</button>
          <div *ngIf="!canDelete">
              <button mat-raised-button color="warn" type="button" disabled>Delete</button>

Here, the public variable canDelete determines whether the node can be deleted or not.

A demo of the working is shown below.

Enjoy Programming!!!

%d bloggers like this: