Showing a heading based on a value in Angular: A Complete Guide

I am attempting to dynamically change the title based on the item's _id value. I have stored the item in the component. Here is the HTML code I am using:

<h1 mat-dialog-title>{{item._id ? "Update" : "Add"}} animal</h1>

Below is my dialog-overview-example.ts file:

import {Component, Inject} from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';

/**
 * @title Dialog Overview
 */
@Component({
  selector: 'dialog-overview-example',
  templateUrl: 'dialog-overview-example.html',
  styleUrls: ['dialog-overview-example.css'],
})  
export class DialogOverviewExample {

  animal: string;
  name: string;
  item:string;

  constructor(public dialog: MatDialog) {}

  openDialog(): void {

  item =[{"_id": "2","animal":"lion","weiht":"100"}];
    let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '250px',
      data: { name: this.name, animal: this.animal,item: this.item }
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.animal = result;
    });
  }

}

@Component({
  selector: 'dialog-overview-example-dialog',
  templateUrl: 'dialog-overview-example-dialog.html',
})
export class DialogOverviewExampleDialog {

  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

  onNoClick(): void {
    this.dialogRef.close();
  }

}

Demo

If the _id exists in the item, the heading should display "Update animal", otherwise it should display "Add animal". In our case, because the id is present in the item, it should show "Update animal". Can you assist me with this?

Answer №1

It appears that the item has been declared as an array within the component. To address this, you should include the given HTML code snippet:

<h1 mat-dialog-title>{{item[0]._id ? "Update" : "Add"}} wildlife</h1>

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

Preventing pageup/pagedown in Vuetify slider: Tips and tricks

I am currently using Vuetify 2.6 and have integrated a v-slider into my project. Whenever the user interacts with this slider, it gains focus. However, I have assigned PageUp and PageDown keys to other functions on the page and would like them to continue ...

How can I ensure that the state is only updated after the map function has finished executing in React?

I am encountering an issue with updating the state after mapping over an array of ids using an async function. The goal is to store the result in newArr and then update the state via setState. However, the state is being updated before the mapping operatio ...

I am finding my program to be lacking efficiency. Is there a more concise method for solving this issue?

Starting off with my journey in Javascript, I am eager to tackle problems and enhance my skills. One challenge that came my way is the following question. Despite my efforts to solve it step by step, I feel like there might be room for improvement in my co ...

Is there an animation triggered by hovering the mouse over?

I've implemented a bounce animation that is triggered by mouseover on an image. Currently, the animation only happens once, but I want it to bounce every time the mouse hovers over it. Here is the HTML code: <div class="hair"> <img src= ...

When the oncuechange event is triggered, it initiates a smooth fade-in/fade-out animation within the HTML P tag

Just starting out with web development and learning JavaScript. Trying to create a webpage that displays lyrics synced with an audio file inside a p tag. The subtitles are sourced from a vet file extension and I am using the "cuechange" event in JavaScript ...

unable to assign values to this.props (appears as undefined or an empty array)

Upon setting up react/redux, I encountered a peculiar issue. When my component mounts, it should render the information stored in this.props.heroes.data. However, upon logging this data, I receive an unexpected value of [{id:1,heroname:'Batman',r ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

Creating a pop-up window in Shiny that activates when switching tabs

Is there a way to create a popover/tooltip in a Shiny app that automatically appears when users switch to a specific tab containing a data table? I have tried using the shinybs package to create a popover that shows on click or hover, but I need it to appe ...

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

Bidirectional linking using URL query parameters and form inputs (select boxes and sliders)

Presently, I am able to retrieve the GET parameters using $location.$$search. Nevertheless, I am still unsure about how to implement 2-way binding for both the URL and FORM in the following scenario. In the demo image below, when a user updates the FORM ...

My CSS files are not being included by grunt-bower-install

As someone who is relatively new to bower and grunt, I'm struggling with some basic tasks. After running bower install --save bootstrap, my goal is to use grunt-bower-install to update my js & css files as per the instructions on their documentat ...

Issue with JavaScript Date.parse function not functioning as expected

I have implemented a date validation method in my application to check if a given date is valid or not. myApp.isValidDate = function(date) { var timestamp; timestamp = Date.parse(date); if (isNaN(timestamp) === false) { return true; } return ...

Instructions for adding and deleting input text boxes on an ASP.NET master page

*I am currently facing an issue with adding and removing input textboxes for a CV form using ASP.NET in a master page. Whenever I click on the icon, it doesn't seem to work as intended. The idea is to have a textbox and an icon "+" to add more textbox ...

What is the best way to create a mirror effect on one div by clicking another div?

I have created a schedule grid and I am looking for a way to allow users to click on the UK hour and then have the corresponding U.S time highlighted. Is there a CSS solution for this? The functionality I need is to be able to select multiple hours. I have ...

Troubleshooting ng-repeat in AngularJS: Multi checkbox filter malfunction

My AngularJS app has multiple age range filters implemented, but one of them is not functioning correctly and I can't figure out why. You can view a functional example here. The various filters are defined as follows: .filter('five', func ...

Transferring session data through AJAX in PHP

I'm currently developing an app using PhoneGap. However, PhoneGap only supports HTML, CSS, and JS, not PHP. This led me to the workaround of placing the PHP file on a remote server and using AJAX to call it via the server's URL. My issue now is ...

Is there a way to turn off TypeScript Inference for imported JavaScript Modules? (Or set it to always infer type as any)

As I attempt to utilize a JS module within a TypeScript File, I encounter errors due to the absence of type declarations in the JS module. The root cause lies in a default argument within the imported JS function that TypeScript erroneously interprets as ...

What is preventing me from mapping an array to Material UI Chip components?

I'm currently working with Next.js and I'm trying to map an array of elements to Material-UI chip components. However, when I compile the code, I encounter the following error: Error: Element type is invalid: expected a string (for built-in comp ...

Reading JSON documents in JavaScript through multiline strings

Having a JSON document with multiline string data is causing issues for me. I have attempted multiple options, but none of them have successfully solved the problem. For example: [ { "someString" : "A rather long string of English text, an error m ...