How to toggle code block visibility in Angular's ngOnInit() method

I'm currently analyzing different design patterns to optimize the number of REST calls when implementing a 'save while typing feature'. To provide a general overview, in my ngOnInit() function, I have included the following code snippet (with distinctUntilChanged() implementation to avoid excessive REST endpoint calls):

ngOnInit(): void {
      if (this.formIsEditable) {
            this.inputField.valueChanges.subscribe(() => //do REST);
            }
}

The issue I am facing is that formIsEditable is set to true after the component has been initialized, which prevents it from entering the above code block. Is there a method in Angular to trigger an update when this boolean value changes? Essentially, I want to prevent sending a PUT request to the Back End when the boolean is false, and allow it only when the boolean is true.

Answer №1

How about considering this approach:

this.inputField.valueChanges.subscribe(() =>
     if(this.formIsEditable){  //perform REST operation}   
 );}

Remember to always unsubscribe from the observable when done.

Answer №2

To filter values emitted when this.formIsEditable is false, you can make use of the RXJS filter operator. See the example implementation below:

this.inputField.valueChanges
  .pipe(
    filter(_ => this.formIsEditable) 
  )
  .subscribe(() => //perform desired action);

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 pass props to component data using Vue framework

I'm facing an issue with passing props in my component to the same component's data object. For some reason, I'm only receiving null values. Does anyone have any suggestions on how I should approach this problem? It seems like my Vue compone ...

Utilizing the import feature for structuring the routes folder in Express with Node.js

Recently, I made the switch to using ECMAScript (ES6) for my NodeJS Rest API with Express, and I've encountered a few challenges when working with the new keyword import In the past, I would organize my routes folder like this: Let's imagine th ...

Aligning form elements horizontally with Angular 2 Material

Thank you in advance for taking the time to assist me. Your help means a lot! I have developed a form using Angular 2 Material Design and I am facing an issue with aligning two elements. Specifically, how can I align Bill Number and Year as shown in the s ...

Update a specific form data field within an Angular application

I recently encountered a situation where I had an angular form with 9 fields and submitted it to the server using a post request. However, I realized that I had only filled in values for 8 fields while leaving one as null. Now, in a new component, I am w ...

The drag and drop feature seems to be malfunctioning in the Selenium Webdriver when using the Node.js (JavaScript) test automation framework

I am currently utilizing the selenium webdriver along with a customized automation framework built in nodejs. My goal is to implement drag and drop functionality for a slider using the actions class, but unfortunately I am encountering issues. Below you ca ...

Guide on utilizing the <source> tag within v-img component in Vuetify.js?

When it comes to using webp images instead of jpg or png, some browsers may not support the webp format. In such cases, we can use the html tag < source > as demonstrated below, ensuring that at least a jpg image is displayed: <picture> < ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

In order to conceal the div tag once the animation concludes, I seek to implement React

I'm currently using the framer-motion library to add animation effects to my web page. I have a specific requirement where I want to hide a div tag used for animations once the animation is complete. Currently, after the animation finishes, the div t ...

Invoke the REST API and save the compressed file onto the local machine

This is the code snippet I currently have: jQuery.ajax({ type: "GET", url: "http://localhost:8081/myservicethatcontainsazipfile", contentType:'application/zip', success: function (response) { console.log("Successful ...

"An issue with AngularJS ngTable causing a delay in the rendering of Ajax

Struggling with ngTable Setup Having trouble mastering the use of ngTable by going through the ngTable ajax demo. I attempted to follow along with the example as closely as possible, but I'm encountering a deviation in defining an ngResource inline w ...

Obtain an array as the response from an Ajax call

When passing data using Ajax request, I utilize the code below: var query = { "username" : $('#username').val(), "email" : $('#email').val(), } $.ajax({ type : "POST", url : "system/process_registration.php", ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...

The quiet harmony of FeathersJS and Socket.io as they attentively listen to events is

I've been working hard to get everything set up and running smoothly, but it seems like I'm stuck on the last piece of the puzzle. Despite following the documentation closely, I can't seem to figure out what I'm missing. Here is the @an ...

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...

Expressjs route encountering issue with imported database function failing to return a value

Currently, I am in the process of creating a REST API using Expressjs. Initially, all routes were integrated into one main file. However, I have now separated these routes, database connection, and database methods into their individual files. login-db.js ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

Sample Angular component showcasing arguments and content within a storybook MDX preview

We showcase our angular components using Storybook and typically utilize the MDX format for this purpose When dealing with an angular component that needs content and accepts properties (via the "Controls" Plugin), I am facing difficulties in implementing ...

Discover the position within a two-dimensional array

Suppose I have an array that contains objects, and each object has its own id property. In this case, I can find the index by writing: data.findIndex(x=>x.id === newData.id); Now, if data is an array of arrays of objects, how can I efficiently get two ...

Deleting a file and value in JavaScript

Can you help me figure out how to remove the value of q when the .close class is clicked? Here's my code: $(document).on('click', '.close', function () { $(this).parents('p').remove(); }) $('#Q1DocPath'). ...