Different or improved strategy for conditional rendering in Angular

Hey there! I've got a few *NgIf conditions in my template that determine which components (different types of forms) are displayed/rendered. For example, in one of my functions (shown below)

private _onClick(cell:any){
        this._enableView = false;
        this._enableCreate = true;
        this._enableDelete = false;
        this._enableEdit = false;
    }

I use it to enable the create form in the template and hide other forms if they're present. However, I'm starting to feel like this approach is a bit off or repetitive. Is there a better suggestion or alternative method I could consider instead?

Answer №1

If Leguest's suggestion of having a single state is feasible, my recommendation would be to utilize the ngswitch directive in this manner:

// Example of ngSwitch
<div [ngSwitch]="state">
    <div *ngSwitchCase="'create'"> ... </div>
    <div *ngSwitchCase="'view'">  ... </div>
    <div *ngSwitchCase="'edit'"> ... </div>
    <div *ngSwitchCase="'delete'"> ... </div>
    <div *ngSwitchDefault> ... </div>
</div>

Alternatively, if you are working with Angular 4.x, you can make use of ngIf else:

// Syntax for ngIf/Else
<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<template #elseBlock>Falsy condition</template>

Answer №2

It's hard to say if it's an improvement or not, but one approach is to have a single state property like this.state, which holds a string value:

JavaScript

 private _onClick(cell:any){
    this.state = 'create'
 }

HTML

<div *ngIf="state == 'create'">
    // create form 
</div>
<div *ngIf="state == 'view'">
   // view form
</div>
<div *ngIf="state == 'edit'">
  // edit form
</div>
<div *ngIf="state == 'delete'">
 // delete form
</div>

This allows you to move some of your code into templates, potentially streamlining your JavaScript codebase.

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

Managing multiple changes in input values within an object

Looking to update multiple input field values using the handleChange() method with a starter object that includes its own properties. The goal is to assign input field values to corresponding properties within the starter object. However, the current imple ...

Ensure that the HTML input element only accepts positive values, including decimal numbers

I need to build an input field that only accepts positive numbers, including decimal values. Leading zeros are not allowed, and users should not be able to paste invalid values like -14.5 into the field. Here is my current implementation: <input type= ...

Multiple change events triggered in AJAX interactions

Having a list of doctors in a dropdown menu with an ID of "doctors", I use AJAX to fetch related locations based on the selected doctor. These retrieved locations are then displayed in another dropdown menu with an ID of "locations". Subsequently, chan ...

Encountering an unhandled promise rejection issue with Knex's batchInsert function when attempting to insert arrays larger than 3 elements

I am currently working on an express app and utilizing Knex as the query string builder. During batch insert operations with an array of 1000+ objects, I encountered an error when the array exceeded a certain length. The specific error message is provided ...

AngularJS Kendo Date Picker: A Simplified Way to Select

Having trouble with formatting dates in my local timezone, the date picker is displaying it incorrectly. Here's an example of the code: input id="logdate" kendo-date-picker="logdate" k-options="logdateOptions" data-ng-model="logFilter.date" k-ng-mode ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...

Replace the hyphen with a comma using JavaScript

Looking for a way to modify a string like this: "PALS español K- add-on" by replacing the - with ,. The desired output should be: "PALS español K, add-on" Is there a JavaScript solution to achieve this task? ...

How can I dynamically adjust the stroke length of an SVG circle using code?

In my design project, I utilized Inkscape to create a circle. With the fill turned off, only the stroke was visible. The starting point was set at 45 degrees and the ending point at 315 degrees. After rotating it 90 degrees, here is the final outcome. < ...

What is the recommended service to call in an Angular unit test?

Greetings! Currently, I am in the process of writing unit test cases using Jasmine. My focus lies on interacting with various restful APIs within my components. The specific functionalities I am testing include deletion and addition of users. To facilitate ...

Changing a JavaScript command into a text representation

Currently, I have an array stored in a variable as shown below: arr = [1, 2, 3] Is there a way to convert this array statement into a string like this? newArr = "arr = [1, 2, 3]" ...

When trying to click a button in an ion-footer, the (click) function may not execute initially

I have been working on creating a chat feature with Ionic 2, utilizing the keyboard-attach directive. //View <ion-footer [keyboardAttach]="content"> <ion-toolbar class="text_send"> <ion-textarea class="textarea" fz-elastic ...

Sending messages to all sockets in socket.io except the one who sent it

I'm currently working on integrating a chat feature into my app using socket.io. The process involves sending an API request to the server each time a user sends a message, which is then stored in the database. Only after this data storage step is com ...

Iterate through the form fields and save the information into an object

I am attempting to create a JavaScript object by looping through form inputs. const data = {}; // loop through each input found in form $('#form_name').filter(':input').each(function() { const $id = $(this).attr('id'); c ...

Tips on customizing label colors on a Donutchart using Google API

https://i.sstatic.net/Rpor0.png I am looking to change the color of 12.5 (to Green) and 25 (to red) based on the donut arc color in Google Charts. Below is the code snippet: var container = document.getElementById('chart_div'); var chart = new ...

Unexpected outcomes arise when parsing headers from a file-based stream

Currently, I am in the process of creating a small parser to analyze some log files using node streams (more specifically io.js). I have been referring to the documentation for unshift to extract the header. While I can successfully divide the buffer and ...

issue with the emit() and on() functions

While diving into my study of nodejs, I encountered a puzzling issue where emit() and on() were not recognized as functions. Let's take a look at my emitter.js file function Emitter(){ this.events = {}; } Emitter.prototype.on = function(ty ...

Leveraging $last in Angular for obtaining the final visible element with ng-show

My ng-repeat container div contains multiple images, each with a corresponding div next to it. Using $last, I can make sure only the div of the final image is visible after all images. However, I also have a filter button on the page that hides certain im ...

Determine the number of Fridays that fall between two dates using JavaScript or jQuery

Can you help me calculate the total number of a specific day between two given dates? For instance, if I have a start date and end date stored in a variable, I would like to know how many Fridays fall within that timeframe. ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

Angular JS presents an exciting feature called Multiple Filters, which allows

I have a data representation application that displays information in table format with columns id, name, price, quantity The data is presented using ng-repeat. You can view it on this Plunker <body ng-controller="myController"> <h1>Data< ...