Tips for utilizing ngIf based on the value of a variable

Here is the code from my file.html:

<button ion-button item-right>
        <ion-icon name="md-add-circle" (click)="save();"></ion-icon>
      </button>

The content of file.ts is:

editmode = false;

I am trying to achieve the following: If editmode is set to false, then execute the save() function. However, if it is true, I want to call the editedu(elem,index) function when the button on the HTML page is clicked.

Answer №1

Simply use the following code snippet:

<button ion-button item-right>
 <div *ngIf="editmode">     
<ion-icon name="md-add-circle" (click)="editedu(elem,index);"></ion-icon>
</div>
 <div *ngIf="!editmode">     
<ion-icon name="md-add-circle" (click)="save();"></ion-icon>
</div>
</button>

If you prefer doing it in a single line, you can use this shorter version:

<div   *ngIf=editmode ? save() : editedu(elem, index)">
   <ion-icon name="md-add-circle" (click)="save();"></ion-icon>
</div>

Answer №2

To decide whether to save or edit education information based on the 'editmode' variable, you can utilize a ternary if statement. Alternatively, you could invoke a method that, in turn, calls another method depending on the value of 'editmode'.

(click)="editmode ? save() : editedu(elem, index)"

Answer №3

Have a look at the plunker demo https://plnkr.co/edit/X5e6avkveGeVRqhzLVFr?p=preview

//our main component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)='editMode = !editMode'>Toggle editMode {{editMode}}</h2>
      <button (click)='editMode? save(): ""'>Call Me</button>
    </div>
  `,
})
export class MainComponent {
  name:string
  editMode: boolean = true;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  save(): void {
    alert("Called because editMode is true");
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ MainComponent ],
  bootstrap: [ MainComponent ]
})
export class MainModule {}

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

Angular - Set value on formArrayName

I'm currently working on a form that contains an array of strings. Every time I try to add a new element to the list, I encounter an issue when using setValue to set values in the array. The following error is displayed: <button (click)="addNewCom ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error. ...

What are the steps to retrieve the original source code of an HTML file, specifically in Angular 2 RC4

Is there a way to retrieve the source code that I manually typed in my IDE using JavaScript? Note: I am working with angular2 rc4. I attempted to access it using Reflect.getMetadata, but encountered errors indicating that it is not functioning properly. ...

typescript error: referencing a variable before assigning a value to it in function [2454]

I am currently in the process of creating a store using nextJS I have two variables that are being assigned values from my database through a function let size: Size let ribbonTable: Ribbon async function findSizeCategory(): Promise<v ...

Utilizing Mongoose to fetch data from Atlas MongoDB for integration into an Angular application

I recently made some updates to my signup page by adding a new input field for the user's name and adjusting the schema settings accordingly. How can I now retrieve this name to use in both my post-list component and post-create component? Here is an ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

Trouble occurs in the HTML code when trying to access a property from an inherited interface in Angular

Currently, I am working with Angular 17 and have encountered a specific query: In my project, there is an IDetails interface containing certain properties: export interface IDetails { summary: Summary; description: string; } Additionally, there is an ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

The duration of recorded audio in JavaScript is unclear

I managed to successfully create a structure for recording and downloading audio files. However, I'm facing an issue where the final downloaded file has an unknown duration. Is there any way to solve this problem?? Here is my Typescript code snippet: ...

Mat-button click event is unresponsive when Mousemove is triggered on a smartphone using material.angular

I have encountered an issue with Angular Material. Everything works smoothly on a desktop browser, but when using a smartphone or developer tools in Chrome, I noticed that the (click) event of a button does not fire if you move the cursor even by just one ...

Learn how to break down Angular 2 with Typescript in just 5 minutes by troubleshooting issues

I've been delving into the world of TypeScript and Angular 2 by following the guide at https://angular.io/guide/quickstart. After going through all the steps, I encountered some errors with the final step npm start. Here's what I got: Microsoft ...

Choosing the most suitable stylesheet in Angular 8 when multiple CSS files are present

In my project, I have several CSS stylesheets for angular components. I am curious if there is a method to designate a preferred stylesheet when multiple sheets loaded by a component contain the same styles but with different values. ...

In order to launch an Angular project

Currently, I am in the process of creating a VSS web extension using Angular... To generate a .vsix file, I need to reference an HTML file. The challenge arises when working with Angular because we typically use ng serve which loads our page at http://lo ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

Instructions for accessing the side menu upon navigating to a new page

I'm working on an Ionic4 app that integrates with Google Firestore and includes a login feature. My goal is to have the sidemenu automatically open whenever a user logs into the application. For example: Login > PageX > *Open Sidemenu. How can I achi ...

What is the best way to ensure all keys of a certain type are mandatory, while still allowing for the possibility of

I am looking to create a mapping of key/value pairs for a specific type in the following way: required_key: string | undefined transformed to required_key: string | undefined (remains the same) required_key: string transformed to required_key: string (rem ...

Exploring TypeScript: Implementing a runtime data mapping in place of an interface

Take a look at this code snippet that defines two command handlers for a server: import { plainToClass } from "class-transformer"; enum Command { COMMAND_1, COMMAND_2, } class Command1Data { foo1!: string } class Command2Data { foo2!: ...

Testing Angular applications using Karma

After utilizing the yo angular 1 generator, it generated a landing page and some tests. However, I am facing an issue when trying to compile the code in VS as I receive an error stating that "module('fountainFooter');" is undefined. /// <refe ...

Fixing the issue of 'Unrecognized character < in JSON at position 0 at JSON.parse'

I have recently deployed my Angular 6 application on Heroku at . However, upon deploying, I encountered the error message: SyntaxError: Unexpected token < in JSON at position 0 during JSON.parse. I am aware that this error occurs when the response ret ...