Conditionally show a button in an Angular application based on the truthiness of a boolean value

I'm currently developing a simple angular Single Page Application (SPA) for a Pizzeria.

Within my application, I have an array that contains various types of Pizzas with string, number, and boolean data types.

Using this array, I am dynamically generating cards using Bootstrap, displaying the pizza's name, price, description, image, and availability status.

If a pizza is marked as available (true), I want to display "Details" and "Order" buttons for that specific dish. If it's unavailable (false), I only want to show the dish's image with a message stating "Not available".

Here is a snippet of my array:

export const pizze = [
    {
        name: "Margarita",
        price: 13,
        description: "Tomato Cheese Fior di Latte",
        image: "https://cdn.pixabay.com/photo/2016/03/05/21/47/american-1239091_960_720.jpg",
        available: false
    },
    {
        name: "Marinara",
        price: 10,
        description: "Tomato, Garlic, Oregano",
        image: "https://cdn.pixabay.com/photo/2016/03/05/21/47/american-1239091_960_720.jpg",
        available: true
    },
    {
        name: "Quattro Formaggi",
        price: 15,
        description: "Tomato and 4 different cheeses",
        image: "https://cdn.pixabay.com/photo/2016/03/05/21/47/american-1239091_960_720.jpg",
        available: true
    },
    {
        name: "Diavola",
        price: 14,
        description: "Tomato cheese salami pimento de padron",
        image: "https://cdn.pixabay.com/photo/2016/03/05/21/47/american-1239091_960_720.jpg",
        available: false
    },

I've defined the various data types in a separate ts file:

export interface Imenu {
    name: string;
    price: number;
    description?: string;
    image: string;
    available: boolean;
}

Next, I created Bootstrap cards with a specific layout and utilized ngIf Else statements to handle the availability logic:

  <div class="card" *ngFor="let val of menuArr; index as i">
            <img src="{{val.image}}" height="350px">
            <div class="card-body">
                <h5 class="card-title">{{val.name}}</h5>
                <p class="card-text">{{val.description}}
                </p>
                <p>{{val.price}}€</p>
                <p *ngIf="val.availabilty; else variableName">
                    <button type="button" class="btn btn-primary">Details</button>
                    <button type="button" class="btn btn-success">Order</button>
                </p>

                <ng-template #variableName>
                    <p>Not available</p>
                </ng-template>


            </div>
        </div>

menu/menu.component.html:11:20 - error NG5002: Parser Error: Unexpected token ; at column 27 in [{{val.availabilty}}; else variableName] in /Users/Michael/Desktop/CodeFactory/Code Review /CR3/FE20-CR3-Almhofer/FE20-CR3-Almhofer/CR3/src/app/menu/menu.component.html@10:19

11 <p *ngIf="{{val.availabilty}}; else variableName"> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

menu/menu.component.ts:6:16 6 templateUrl: './menu.component.html', ~~~~~~~~~~~~~~~~~~~~~~~ This error is occurring in the MenuComponent template.

I'm encountering this error. Can someone provide the correct syntax to check the boolean value from my array and correctly display the availability of each dish?

Answer №1

Avoid using interpolation ({{}}) within the *ngIf directive, as it is designed to work with boolean expressions. The correct syntax for the *ngIf directive is shown below:

<p *ngIf="val.availabilty; else variableName">
    <button type="button" class="btn btn-primary">Primary</button>
    <button type="button" class="btn btn-success">Success</button>
</p>

Answer №2

Initially, the = operator is being utilized, which serves as an assignment function rather than an equality check. It is advisable to exercise caution and implement == or === in the given code snippet:

{{val.availabilty}} = true

As per the official documentation, you have the option to use an expression similar to the one provided below:

<p *ngIf="val.availabilty; else variableName">

This scenario aligns well with the application of the abbreviated syntax, which would appear as follows (the sole contrast being the absence of a semicolon):

<p *ngIf="val.availabilty else variableName">

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

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

Tips for elegantly merging two Observables within an RXJS pipeline

I am working on developing a log viewer using Angular. Upon user entry, I aim to load historical logs and also begin monitoring for new logs. Users have the ability to filter logs using a simple form that emits a query object. Each time the query changes, ...

Exploring alternatives for navigation in nebular without using the global spinner

I am currently working on customizing the nebular ngrx-admin template. There is a global spinner that shows up when navigating from the header to a new page (component). I want to hide this spinner, specifically for certain components where it's not n ...

Place the delete and edit buttons on the right side of the card

I am trying to align the edit and delete buttons with the image and premise name on the same line. Both buttons should be placed on the right side and have the same size as the card. Currently, the layout looks like this: https://i.sstatic.net/sNikU.png ...

Troubleshooting an angular problem with setting up a dynamic slideshow

I am currently working on building a slideshow using plain HTML, CSS, and JavaScript. I referred to the following example for guidance: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto However, despite implementing the code prov ...

What is the process of attaching a property to every object within an array using TypeScript?

In my search for adding a property to each object in an array, I came across a solution in AngularJs on Stack Overflow. However, I attempted the following approach which did not yield the desired outcome. Any assistance would be greatly appreciated. ex ...

Is there a way to make Typescript accept dot notation?

Is there a way to suppress the compile time error in Typescript when using dot notation to access a property that the compiler doesn't know about? Even though using bracket notation works, dot notation would be much more readable in my specific case. ...

Different ESLint configurations for mjs, js, and ts files

For my project, I've set up ESM (.mjs) files for server-side code, CommonJS (.js) for tooling, and TypeScript (.ts) for the client side. In VS Code, when I look at CommonJS files, I'm getting errors related to requires such as "Require statement ...

How can I make TypeScript properly export function names for closure-compiler?

Here is the TypeScript code I am working with: namespace CompanyName.HtmlTools.Cookie { export function eraseCookie(name:string, path:string) { createCookie(name, "", path, -1); } export function readCookie(name:string) { ...

Ways to conceal a table and button in the absence of data for display

I've been working on a way to hide the table and the 'changeState' button when there's no data present. Currently, I have set it up so that a message saying 'No entries in the list!' pops up briefly before disappearing, bringi ...

Utilizing conditional types for type narrowing within a function's body: A comprehensive guide

I created a conditional type in my code that constrains the second argument of my class constructor based on the type of the first argument. Although the type checker correctly limits what I can pass to the constructor, I am struggling to get the compiler ...

Event listener for scrolling in Angular Dart component

I am looking to implement a functionality where a "back to top" button appears once the user has scrolled the page by 500px. I have been trying to capture the scroll event in the main Div of my AppComponent. <div class="container" scrollable&g ...

What sets apart Object.assign {} from Object.assign []?

While reviewing code done by a previous developer who is no longer with us, I observed that they sometimes used Object.assign({}, xyz) and other times they used Object.assign([], abc); Could there be a distinction between the two methods? ...

Error Encountered When Searching for Modules in a Yeoman-Generated Express TypeScript Project

After generating an express typescript project using yeoman, I encountered some errors whenever I tried running the application. The errors stated that it could not find modules such as "morgan", "body-parser", and "cookie-parser". Even though these module ...

What is the best way to change the color behind the SVG to black?

I'm having some trouble creating a signup form with SVG logos. The colors seem to clash and no matter what I do, the color doesn't change from white. My goal is to have the actual SVG logo remain white while the background behind it is black. He ...

Is there a way to enable hover functionality on mobile devices? I wish for the hover effect seen on desktop to be triggered automatically on mobile devices

I attempted to implement @media (hover: hover) without success. In my design, I have three images in a row that reveal a text overlay when hovered over with a mouse. However, the issue arises when I try to switch to a mobile view, as the images remain un ...

Why am I encountering numerous errors while attempting to install Juice Shop?

My attempt to install the juice shop app from GitHub resulted in 63 errors showing up after running the command npm install. [riki@anarchy]: ~/juiceShop/juice-shop>$ npm install (Various warnings and engine compatibility issues) Multiple vulnerabilit ...

Ways to center a spinner on the screen using CSS during loading

Upon loading the page, my spinner appears in the center of the screen after a second. However, in the initial frame of the page, it is not centered but positioned on the top-left corner instead. How can I ensure that my spinner starts off centered from the ...

Before users can apply any filters, all items must be loaded into an Observable<Hero[]> array

Is there a way to modify the Angular 2 Tour of Heroes search component so that it displays all items on page load (showing all Heroes) and then makes a new request to get filtered results only when a filter is provided? import { Component, OnInit } from & ...

Angular virtual scrolling not populating the list with data

I have encountered a challenge while trying to implement infinite virtual scroll on an Angular 7 project with a GraphQL backend from Hasura. I am puzzled by the fact that the new data is not being added and there are multiple API requests being made when ...