Ways to invoke a function in Angular2 when the Boolean condition is met

Within my component class, I have implemented a popup function along with a Boolean flag that returns true or false based on specified conditions. In the template class, I want the popup function to be triggered when the flag becomes true, displaying a popup dialog box. However, I am unsure of the correct approach to achieve this. Any assistance in guiding me towards the right solution would be greatly appreciated.

<ng-template #sessionSuccessModal let-c="close" let-d="dismiss">
<div class="modal-header">
<h4 class="modal-title">Include Criteria Error</h4>
<button type="button" class="close" aria-label="Close" (click)="closeModel()">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body"  class="bg-light text-dark">
<p>{{ alertMessage }}!</p>
</div>
<div style="text-align: center" class="bg-light text-dark">
<button type="button"  (click)="closeModel()">Ok</button>

</div>
</ng-template>

The initial state of 'commaSeparation' is set to false, and then later validated using 'validateMultiComma()' from 'genericValidator'. If the validation returns true, I need to invoke the 'displayModel()' alert method. Currently, the popup functionality is working as expected within 'ngAfterViewInit()', but an error is being logged in the console.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-untouched: true'. Current value: 'ng-untouched: false'

 ngAfterViewInit() {
        let controlBlurs: Observable<any>[] = this.formControls
            .map((formControl: ElementRef) => Observable.fromEvent(formControl.nativeElement, 'blur'));
// debounceTime(1000)/
        Observable.merge(this.orderUnitForm.valueChanges, ...controlBlurs).subscribe(value => {
            this.displayMessage = this.genericValidator.processMessages(this.orderUnitForm);
           // this.valid = this.genericValidator.validateControls(this.orderUnitForm);
        });
        this.orderUnitForm.valueChanges.debounceTime(1000).subscribe(value => {
            this.valid = this.genericValidator.validateControls(this.orderUnitForm);
            this.commaSeparation = this.genericValidator.validateMultiComma(this.orderUnitForm);
              if(this.commaSeparation == true){
                this.displayModel();
              }
        });
  }

Below is the implementation of my 'dispalyModel()' function:

displayModel() {
     this.alertMessage = 'You cannot enter more than one multiple at the same time ';
     this.successErrorModalBlock = this.modalService.open(this.sessionSuccessModalref);
   }

Answer №1

To accomplish this, you can implement the OnChanges interface, which is a lifecycle hook in Angular.

import { Component, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnChanges  {

  // defining the flag property
  commaSeparation: boolean;

  ngOnChanges(changes: SimpleChanges){
    if (changes['commaSeparation'] && changes['commaSeparation'].currentValue){
        this.showPopup();
    }
  }

  public showPopup(){
        alert('Replace this alert with code that will display your popup');
  }
}

Resource: https://angular.io/guide/lifecycle-hooks#onchanges

Answer №2

It is generally not recommended to invoke functions with side effects within an angular expression. Angular may call these functions multiple times to ensure consistency in the result. Instead, use functions in expressions to return a value rather than trigger an action.

For a better approach, consider calling popupAlert from your controller like this:

$scope.$watch('commaSeparation', function(commaSeparation) {
        // The value of commaSeparation has just changed. Alert if it changed to true!
        if (commaSeparation) {
            popupAlert();
        }
    });

Answer №3

When dealing with the input property commaSeparated, you have the option to implement a property change watcher using the lifecycle hook ngOnChanges. By doing so, you can conditionally call popupAlert whenever the value of commaSeparation changes (link to docs).

@Component({
...
})
export class MyComponent implements OnChanges {

  // ...

  @Input()
  commaSeparation = false;

  // ...

  ngOnChanges(changes: SimpleChanges) {
    const commaSeparationChanges = changes.commaSeparation;

    if (commaSeparationChanges && commaSeparationChanges.currentValue) {
      this.popupAlert();
    }
  }
}

If commaSeparated is only modified within the component itself, consider making it private and utilizing a getter/setter pair to handle triggering the popup:

@Component({
...
})
export class MyComponent implements OnChanges {

  // ...

  private _commaSeparation = false;

  // ...

  get commaSeparation() {
    return this._commaSeparation;
  }

  set commaSeparation(value) {
    this._commaSeparation = value;

    if (value) {
       this.popupAlert();
    }
  }
}

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

Start progress bars on several divs that share a common class

I'm attempting to utilize the ProgressBar.js Plugin on multiple div elements that share the same class form-progress This is my HTML code: <div class="form-progress"></div> And here is the corresponding JavaScript code: var form_pr ...

Is the NodeJS debugger prone to crashing when utilizing `this` to invoke an unidentified function?

My JavaScript file contains the code below: (function (context) { console.log(123); debugger; })(this); When I run my script in debug mode like this: $ node debug script.js I noticed that the other lines in debug mode are not colored green. Wha ...

Utilize the NPM package manager in the zsh shell on Ubuntu within a Windows 10

After transitioning to the zsh for coding in Python and configuring the environment variables, I am now encountering an issue while trying to start a small JavaScript project. The problem arises when attempting to use npm, as initializing the repo results ...

Tips for retrieving a reactive variable from a setup() method?

I'm currently working on a small notes app and using Vue3 + Typescript to enhance my skills. The following code snippet demonstrates how to dynamically create and display an Array of notes: <template> <q-layout> <div v-for ...

Customize your Google Translate experience by choosing your own option values

Is there a way to trigger the same JavaScript calls by clicking on an option value in an HTML select element as with text-based links in the Google Translate widget? Check out this jsfiddle for more information <html> <body> <select i ...

Facing an issue with displaying a component error in a mat-form-field in Angular 9

I am looking to develop a shared component for displaying errors in Angular Material. Here is my shared component pfa-share-error: <mat-error *ngIf="fieldErrors(fieldName).required && fieldErrors(fieldName)"> Required </mat-err ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

Issue in Vuetify: The value of the first keypress event is consistently an empty string

I need to restrict the user from entering numbers greater than 100. The code snippet below represents a simplified version of my production code. However, I am facing an issue where the first keypress always shows an empty string result. For example, if ...

Leverage the geocode callback function results from Google Maps in NodeJS to render a map on the AngularJS 2 component template

Hey there, I'm currently utilizing the Google Maps Node.js client web API and want to showcase a map on my HTML views using AngularJS 2. I have a server export that sends an object to my AngularJS2 client service const googleMapsClient = require(&ap ...

Execute JS function when navigating back in history

I recently came across an article on browser bfcache in Stack Overflow. I decided to test it out on Safari Version 7.0.5 (9537.77.4) and noticed that when I click the back button in history, the JavaScript does not execute. How can I ensure that my JavaS ...

Having issues delivering static JavaScript files to the client's browser using express.js

I'm looking to create a simple blog application using express.js, where I can write and store posts in a database directly from the browser. After some research, I found the ckeditor package, which allows for formatting before submission. I attempted ...

Retrieving a specific item using its ID from a JSON file with Ionic 5

Newcomer's query For multiple Ionic pages, I require fetching a specific item by ID from a centralized JSON file. The structure of my JSON data is as follows: { "items": [ { "id":"0", "link&q ...

Syntax in Next.js for shallow routing

When working with next js, I want to update the route without refreshing the page. Currently, I am using the following syntax which I find cumbersome: Router.push( `/statistics?entityId=${id}&type=${entityType}&provider=${serviceProvider}`, ...

`Troubleshooting Issue: Autocomplete feature in Jquery Codeigniter not functioning

Having an issue with autocomplete in my codeigniter project. When I input text into the field, a dropdown appears but no values are shown. It looks like this: Screenshot The error displayed in the console is: Screenshoot Below is the relevant code: Mode ...

Is it possible to generate a form dynamically in a Vue.js HTML file based on JSON data? Check out the provided f

Currently, I am diving into the world of vue.js and experimenting with building a dynamically created form. To explain further, I have JSON files that define what input types should be included in the form; now I am figuring out how to implement this usin ...

What might be causing res.download to retrieve a zip file that is empty?

Using expressjs for my app development, I have created a service to download files on the client side using res.download(filepath, filename). The following is the code snippet of my service: router.route('/downloadFile').get(function(req,res){ ...

Failed to install @ngrx/store due to unforeseen issues

Having issues with the installation of @ngrx/store My current setup includes: Node 8.9.3, NPM 5.5.1, Angular CLI 1.7.4, Angular 5.2.0 I am using Angular CLI to create a new Angular application and attempting to add @ngrx/store by running the following c ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

Manipulate md-select options with Angular using setValue

My goal is to update a select option, but I'm having trouble getting it to work properly. When I use this.eventForm.controls.venue.setValue(event.venue.name);, the value of venue changes to match event.venue.name. However, the select option itself doe ...