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

What is the reason why modifying a nested array within an object does not cause the child component to re-render?

Within my React app, there is a page that displays a list of item cards, each being a separate component. On each item card, there is a table generated from the nested array objects of the item. However, when I add an element to the nested array within an ...

MatDialog displaying no content

I found this tutorial on how to implement a simple dialog. The issue I'm facing is that the dialog appears empty with no errors in the console. Even after making changes to my dialog.component.html or dress-form.ts, nothing seems to reflect in the o ...

How can I properly test an Angular pipe that has its own dependencies, which are injected using NG 15 inject()?

For a basic demonstration, within a fresh Angular 15 CLI application: We need to create a new service called HelperService This service will be injected into DemoPipe with the newly introduced inject() method: export class DemoPipe implements PipeTransfo ...

The issue encountered is: "Uncaught promise error: Provider for ActivatedRoute not found."

The dependencies listed in the package.json file are: "dependencies": { "@angular/cli": "1.0.0", "@angular/compiler-cli": "^4.0.0", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angula ...

show the stored value inside the useRef variable

One of my challenges involves a variable const prediction = useRef<any>(null); A button triggers a function that updates the variable's value: function showResult() { classifier.current.classify(capture, (result) => { ...

Utilizing a file type validator in SurveyJs: A guide

Is there a way to validate uploaded documents on a form using surveyJs and typescript with a custom validator before the file is uploaded? The current issue I am facing is that the validator gets called after the upload, resulting in an API error for unsup ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Child component responsible for closing the modalI will guide you through

A component in my project has a header with a modal window that pops up when clicked: <a (click)="open(content)" class="in">Sign in</a> <ng-template #content let-modal> <button type="button" class="close" aria-label="Close" (click)= ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...

Obtain the function's return type without actually executing the function

Consider the following TypeScript function: export const foo = function(){ return { a: 1, b: true, c: 'bar' } }; If I were to import this function into another file: import {foo} from './foobar'; Is there a me ...

How can the file system module (fs) be utilized in Angular 7?

Hello, I am currently working with Angular 7. I recently attempted to utilize the fs module in Typescript to open a directory. However, I encountered an error message stating: "Module not found: Error: Can't resolve fs". Despite having types@node and ...

Error in main.ts due to issues with importing components using an index.ts file

I am facing a common exception: Unexpected directive value 'undefined' on the View of component 'AppComponent' Many solutions I found online did not address my specific issue related to circular dependencies or missing export statem ...

Components for managing Create, Read, Update, and Delete operations

As I embark on my Angular 2 journey with TypeScript, I am exploring the most efficient way to structure my application. Consider a scenario where I need to perform CRUD operations on a product. Should I create a separate component for each operation, such ...

The JSON.stringify method in TypeScript/JavaScript does not align with the json-String parameter or request body in a Java controller

Currently, I am utilizing jdk 1.8 and have a rest endpoint in my Java controller: @PostMapping("/filters") public ResponseEntity<StatsDTO> listWithFilter( @RequestBody(required = false) String filter ) { try { ............... } } A test sn ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...

Struggling to retrieve the most recent emitted value from another component in Angular?

Hello everyone, I am currently attempting to retrieve the most recent updated value of a variable from the component app-confirm-bottom-sheet in the app-bene-verification.ts component, but unfortunately, I am unable to achieve this. Below is the code snipp ...

What are the benefits of incorporating a proxy.conf.json file into an Angular application?

Imagine we have a server running on http://localhost:8080/. Rather than configuring the back-end's base URL from environment.ts file, we can create a proxy.conf.json file with the code below: { "/api": { "target": "http://localhost:8080", ...

Personalized design for Material Tooltip in Angular 17

I am currently working on an angular 17 application that utilizes the latest Material components. My project heavily incorporates the Tooltip component, but I am facing challenges when it comes to customizing it to my preferences. While I did succeed in c ...