How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this:

<navigation 
        [hasNextCategory]="hasNextCategory()"
        [hasPreviousCategory]="hasPreviousCategory()"
        (nextClicked)="nextCategory()"
        (previousClicked)="previousCategory()"
        (submitClicked)="submit()"
</navigation>

This approach seems to be working, but I'm curious about how it actually functions. Are those inputs re-evaluated when an event is triggered from the component, or what triggers the input binding?

Answer №1

Indeed, each time change detection is triggered, the function is executed and its result is assigned to the input property.

If two consecutive calls to the function return different values, an exception occurs in devMode, such as:

hasNextValue() {
  return {};
}

Exception: Expression has changed ...

It is not recommended to bind directly to functions. Instead, assign the result to a property and then bind to that property. Although it can work if you're aware of what you're doing.

update

So, returning true or false based on internal state is not allowed? It's strange because my navigation still functions.

In fact, this practice is permissible. If the state changes due to an event (like a click or timeout), Angular expects those changes during change detection. However, if Angular triggers change detection twice without any relevant event occurring between, it throws the aforementioned exception. The issue arises when change detection itself causes modifications.

The following example would also trigger an exception because change detection modifies the component's state directly (

this.someState = !this.someState;
):

someState:boolean = false;
hasNextValue() {
  this.someState = !this.someState;
  return this.someState;
}

Consequently, two successive calls would produce false and then true, despite no external events.

However, the next example works well:

someState:boolean = false;

@HostListener('click') {
  this.someState = !this.someState;
}

hasNextValue() {
  return this.someState;
}

Here, two subsequent calls will yield consistent results even without any intermediate events.

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

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

jQuery for Revealing or Concealing Combinations of Divs

UPDATE: Check out this answer. I have a complex query related to jQuery/JavaScript. I came across a post dealing with a similar issue here, but my code structure is different as it does not involve raw HTML or anchor tags. Essentially, I am working on ...

How can I modify certain attributes within an array of objects?

https://i.sstatic.net/TKkcV.jpgI need help with updating properties within an object array. Below is my code for reference. I have an object array consisting of two arrays, where the first one contains attribute "first" and the second one contains "last". ...

Stop angular schema form's destroyStrategy from deleting any data

After upgrading my Angular app from version 0.8.2 to 0.8.3 of Angular Schema Form (ASF), a significant bug emerged. The application features multi-page forms that utilize prev/next buttons for navigation. A condition is implemented to display only relevan ...

augmentable form that can be expanded flexibly

Perhaps I'm missing something really simple here, but I just can't seem to figure this out. I'm attempting to create a form that can dynamically extend. The issue I'm facing is that I can't get this particular code to function: & ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Modify a CSS style with JavaScript or jQuery

Can CSS rules be overwritten using jQuery or JavaScript? Imagine a table with rows categorized by different classes - "names" for persons and "company" for companies. How can we efficiently hide or show specific rows based on these classes? If we have a ...

Issue with ASP.NET Core Controller not properly receiving complete JavaScript array object from Ajax call

When passing a JavaScript Object Array through ajax to the controller, I noticed that if there are more than 11 objects in the array, the controller receives it as null. However, with 11 or fewer objects, the array is received successfully. Here is an exam ...

What is the method for implementing a custom layout for the items within a Select component?

I want to customize the options of a Select component by adding HTML elements. Here is an example: <mat-select [(ngModel)]="items"> <mat-option *ngFor="let item of ($items | async)" [value]="item.id"> <span>{{item.name}}</span&g ...

Ways to restrict the maximum length in Draft.js

Is there a way to control the maximum number of characters in draft js? I know how to get the length of the state, but is there a method to prevent the component from being updated past a certain point? var length = editorState.getCurrentContent().getPla ...

Underscore performs calculations and outputs a fresh object as a result

Here is an example of a time series: [ { "_id": { "action": "click", "date": "2015-02-02T00:00:00+01:00" }, "total": 5 }, { "_id": { "action": "hit", "date": "2015 ...

Navigate to the element by clicking on the link, then apply a class to that specific element

I'm currently working with this HTML code: <div id="main"> <p>some text</p> <a id="goto-notes" href="#">see notes</a> <p>some text...</p> <div id="notes"> <p>notes here< ...

What is the best way to generate the message dynamically?

I have implemented the react-intl package for translation purposes in my project. Users have the option to choose between Spanish and English languages, with Spanish being the default language. When a user switches to English, all text should be dynamicall ...

Angular: You cannot assign a type of 'void' to a parameter that expects either a UserCredential or a Promise containing a UserCredential

Upon attempting to initiate a new method following a successful registration, I encountered an error in Webstorm: The argument type 'void' cannot be assigned to the parameter type '(value: UserCredential) => UserCredential | PromiseLik ...

Copying JSON Data in JavaScript: A Guide

Seeking advice on how to duplicate JSON within the same JSON at various hierarchy levels. Take a look at this example JSON below: Initial code snippet looks like this: { "data": { "moduleName": { "content": { "modul ...

Discovering and Implementing Background Color Adjustments for Recently Modified or Added Rows with Errors or Blank Cells in a dx-data-grid

What is the process for detecting and applying background color changes to the most recently added or edited row in a dx-data-grid for Angular TS if incorrect data is entered in a cell or if there are empty cells? <dx-data-grid [dataSource]="data ...

Here's a solution to prevent the "jump" effect when hiding elements in a navbar

Currently, I am facing an issue with my h5 elements within the navbar when scrolling. I am using Bootstrap 4 and jQuery for this project. The problem arises in my navbar where there are four sets containing an icon, followed by an "h5" and then a "p" elem ...

What is the method for inserting a line break following an input element using CSS?

I am utilizing a service that provides me with dynamic HTML containing labels and inputs as shown below: input:after { content: "\a"; white-space: pre; } <label for="username">Username</label> <input type="text" id="username" nam ...

Resize images smoothly without disrupting the anchor scrolling

I have created a website with the following design: (Caution: The site is built using AngularJS on a server that may not serve it correctly - please visit directly instead of using browser reload.) However, I am facing two conflicting requirements... ...