Execute a function once the data has been received from @input in Angular 5

My component receives data from a parent component through an input:

Main Component: main.component.ts

<app-sidebar [data]="programData"></app-sidebar>

In the sidebar component, I have the following:

Sidebar Component: sidebar.component.ts

@Input() data: Entry<any>;

The received data contains a unique ID that is used as a parameter in another function to fetch and populate elements on the page. Currently, I am calling this function inside ngOnChanges, but it gets triggered every time there is a change. Is there a way to call this function only after receiving the data from Input() data for the first time?

Here is my current implementation:

 ngOnChanges() {
    this.id = this.data.fields.id; 
    this.getElements(this.id); 
 }

EDIT

To clarify, I want to set this.id only once when receiving the data for the first time. The incoming data is from an API, so it needs to be processed correctly.

Thank you

Answer №1

UPDATE: In order to only assign the id when the data is set for the first time, you can do so within the OnChanges lifecycle hook by checking if the id has already been set:

ngOnChanges(changes: SimpleChanges) {
  if(changes.data && changes.data.currentValue) {
    const fields = changes.data.currentValue.fields;
    if(fields && (fields.id || fields.id === 0) && (!this.id && this.id !== 0)) {
      this.id = data.fields.id;
      this.getElements(this.id);
    }  
  }
}

If you want to set the id only when it changes, you can use:

ngOnChanges(changes: SimpleChanges) {
  if(changes.data && changes.data.currentValue) {
    const fields = changes.data.currentValue.fields;
    if(fields && (fields.id || fields.id === 0) && fields.id !== this.id) {
      this.id = fields.id;
      this.getElements(this.id);
    }  
  }
}

The OnChanges lifecycle hook accepts a parameter of type SimpleChanges, which should be used to react specifically to changes in the data input.

ngOnChanges(changes: SimpleChanges) {
  if(changes.data && changes.data.currentValue) {
    const data = changes.data.currentValue;
    this.id = data.fields.id;
    this.getElements(this.id);
  }
}

Alternatively, you could utilize a setter for your input:

private _data: Entry<any>;

@Input()
set data(value: Entry<any>) {
  this._data = value;
  this.id = value.fields.id;
  this.getElements(this.id);
}

get data() {
  return this._data;
}

Answer №2

To handle changes in the input value, you can utilize a setter function as shown below:

@Input('data')
set data(value: Entry) {
    // Perform actions with the new incoming data
}

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

Refreshing the inline div styling

I am facing a challenge where I need to update the min-height property of a div using Dojo while keeping all other inline styles intact. Below is the existing HTML snippet for reference: <div id="divid" class="divclass" style="width: 950px; min-height ...

How to Use JQuery Load to Load Google Maps?

Is it possible to ensure that the initialize() function is executed in the correct sequence of events so that a Google Map v3 API map can be loaded via a JQuery .load() method? The current code structure I've implemented is as follows: $('#mapl ...

Problem with Pathjs routing

Can anyone help with this routing issue I'm having? Path.map("/(:page_1)(/:page_2)/").to(funct); The route is not matching for: /projects/index2/ It matches /anything, but not /anything/anything If you have any ideas, please share! ...

Customizing demonstration code for EventDrops with D3.js (by marmelab) - what are the best strategies?

After discovering the non-Node.js version of the EventDrops library for D3 on GitHub, I successfully implemented the example on my own server. You can find more details and the example code in this blog post here. However, I'm currently facing two is ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...

AngularJS OAuth authentication Pop-up: Waiting for JSON response

I am looking to initiate an oauth request in a new window for my project. Here is how I can open the new window: var authWindow = $window.open("/auth/google/signin", ""); After the callback, my server will respond with JSON data: app.get('/auth/ ...

Refresh feature in Angular2/TypescriptRefresh functionality using Angular2/

I am currently working on a mobile project using Angular2, Typescript, and PhoneGap, and I am trying to implement Pull to Refresh functionality without using Onsenui, Ionic, or jQuery due to project limitations. Being a new Angular developer (specifically ...

The combination of the table, thead, and tbody components causes disruptions in the layout of the overall table structure

After creating separate components for table, thead, and tbody and then assembling them on a parent page, the table ends up breaking completely. I'm at a loss on how to resolve this issue. This is the table component: <table> <ng-conte ...

Struggling with developing a personalized editor for React-Data-Grid

For more insights on creating custom editors, the official documentation can be found here. A practical example showcasing a custom color picker can be accessed here. Additional existing editors are available in React-Data-Grid-Addons, located here. Ins ...

Develop a radio button filter utilizing the "Date of Creation" attribute, implemented with either jquery or JavaScript

I am currently utilizing a customized Content Query Web Part to load a series of list items. Each of these items has an XSLT attribute known as the Created Date. Shown below is an example of the markup: <div class="item" createddate="2014-01-22 13:02 ...

Executing multiple commands using Node.js TCP communication

I have established a connection to a serial device via the internet using an ethernet to serial device. The communication is facilitated through a small node.js application. The provided code retrieves the necessary information: var net = require('ne ...

Creating a custom arrow design for a select input field using CSS

I'm currently developing a website (using Wordpress with a custom theme) and I want to incorporate an up/down arrow in the select input field using CSS. The HTML code I have for creating the up/down arrow in the select input field is as follows: < ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

Customized coordinates on leaflet map fail to render

Utilizing the Where the ISS at API to retrieve the current latitude and longitude coordinates of the ISS involves making a serverside request structured like this: app.get("/coordinates", async (req,res) =>{ try{ const result = await axios.get(A ...

Tips for sorting an array of objects by multiple keys while maintaining the order of each key that comes before

I am looking to create a versatile function that can organize an array of objects based on specified keys, while maintaining the order of previous keys. Here is a sample scenario: const input = [ { a: 'aardvark', b: 'bear', c: 'c ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Leveraging the power of react routes for efficient navigation within a react-based application

I am currently facing an issue with setting up routes for a basic react application using react-router. The given routes don't seem to match and the switch defaults to displaying the 404 page. Below is the code for the routes: import { BrowserRout ...

Comma styling in JavaScript

What is the reasoning behind developers choosing to format commas in code this particular way? var npm = module.exports = new EventEmitter , config = require("./lib/config") , set = require("./lib/utils/set"); As opposed to this formatting style? va ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...