The @input field is failing to show the value entered by the user

I'm having trouble with my dynamic reactive form, as the value is not showing up

<div *ngFor="let deliveryAcross of (deliveriesAcross | async)!; let i = index;">
  <app-delivery-across
    [index]="i"
    [deliveryAcross]="deliveryAcross"
  ></app-delivery-across>
  {{ deliveryAcross | json }}
</div>

deliveryacross.component.ts

  @Input("deliveryAcross") deliveryAcross: IDeliverAcross;

  minFormControl: FormControl;
  errorStateMatcher: NextErrorStateMatcher;
  constructor(private change: ChangeDetectorRef, private store: Store) {
    this.deliveryAcross = {
      iso: "",
      min: 1,
      max: 2,
      shippingCents: 0,
      shippingEuros: 0,
    };

    this.minFormControl = new FormControl("", [
      Validators.required,
      Validators.min(1),
    ]);
    this.errorStateMatcher = new NextErrorStateMatcher();
  }

I am unable to use ngModel due to readonly errors, so I opted for using value instead. However, the value is not being displayed and the input keeps refreshing back to empty

<mat-form-field
  class="full-width"
  [@transformRightLeftStateTrigger]="stateDown | async"
>
  <input
    matInput
    [formControl]="minFormControl"
    [errorStateMatcher]="errorStateMatcher"
    placeholder="Minimaal"
    appDeliveryAcross
    [value]="deliveryAcross.min"
    autocomplete="off"
    [key]="'min'"
    [component]="'delivery-across'"
    type="number"
  />
</mat-form-field>

Any idea why the value from deliveryAcross.min is not displaying in the input field?

Answer №1

When you use both the value and formControl as sources of value for an input, the initial value of the formControl takes precedence over the value.

To address this issue, consider using just one source, such as the formControl, and then utilize ngOnChanges to monitor changes in the this.deliveryAcross input and update the formControl accordingly.

You can try the following solution:

ngOnInit() {
  // This section is moved to `ngOnInit` to retrieve the initial value of `this.deliveryAcross` input
  // and set it as the initial value of the form-control.
  this.minFormControl = new FormControl(this.deliveryAcross?.min, [
    Validators.required,
    Validators.min(1)
  ]);
}

// Implement the `OnChanges` interface to detect input changes.
ngOnChanges(changes: SimpleChanges) {
  if(changes.deliveryAcross) {
    this.minFormControl.setValue(this.deliveryAcross?.min);
  }
}
<mat-form-field
  class="full-width"
  [@transformRightLeftStateTrigger]="stateDown | async"
>
  <input
    matInput
    [formControl]="minFormControl"
    [errorStateMatcher]="errorStateMatcher"
    placeholder="Minimaal"
    appDeliveryAcross
    autocomplete="off"
    [key]="'min'"
    [component]="'delivery-across'"
    type="number"
  />
</mat-form-field>

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

Tips for effectively unit testing NgRx selector observables

I'm struggling to replace an NgRx Selector and ensure that the new value is output from the observable. It seems like the call to overrideSelector() isn't functioning as expected. The outcome of this replacement doesn't show up in the final ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

How can I receive the response from a GET request using React Query? I am currently only able to get the response

I have created a search component where I input a name in the request, receive a response, and display it immediately. However, after the first input submit, I get undefined in response. Only after the second submit do I get the desired response. The tec ...

Experiencing a problem in AngularJS 2 after including 'routing' in the imports section of app.module.ts

An issue arises when I include 'routing' in the imports section of app.module.ts app/app.routing.ts(18,23): error TS2304: Cannot find name 'ModuleWithProvider'. [0] app/app.routing.ts(18,65): error TS2304: Cannot find name 'AppRou ...

Storing a byte array in a local file using JavaScript: A Step-by-Step Guide

Recently, I encountered an issue while working with an openssl certificate. Specifically, when I tried to download the certificate from my API, it returned byte arrays that I needed to convert to a PEM file in order to access them through another API. The ...

What is the best way to transfer data from a modal with a form in Ionic 2 to the home page?

Hello everyone, I could really use some assistance. As a newcomer to Ionic and Angular, I am attempting to develop a weather app in Ionic 2. I have set up a Home page that triggers an AddWeather() function through a Click event. The function opens a modal ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

Tips on how to connect with ngFor

I have been working on an application to display various events, but I am encountering an issue. Whenever I load the webpage, it appears empty and the console throws an error saying 'Can't bind to 'ngForEvent' since it isn't a know ...

Execute a function once an observable variable has been successfully initialized

I'm currently putting together a chat application using socket.io in Angular. I've encountered an issue where I can't seem to execute a particular code or function right after an observable variable is initialized through subscription. The i ...

Implementing recursive functionality in a React component responsible for rendering a dynamic form

Hello to all members of the Stack Overflow community! Presently, I am in the process of creating a dynamic form that adapts based on the object provided, and it seems to handle various scenarios effectively. However, when dealing with a nested objec ...

Received corrupted file during blob download in Angular 7

When using Angular 7, I am making an API call by posting the URL file and attempting to download it using the 'saveAs' function from the fileSaver library. The file is successfully downloading, but it appears to be corrupted and cannot be opened. ...

Resetting and marking an Angular2 form as untouched

Is it possible to reset a form and mark it as untouched, clean, etc after submission while staying on the page to avoid resubmission? this.myForm.reset() this.myForm.markAsPristine() this.myForm.controls['options_name'].markAsUntouch ...

What is the best method for managing an event loop during nested or recursive calculations?

When it comes to breaking a computation and releasing using setTimeout(), most examples seen involve having a shallow call stack. But what about scenarios where the computation is deeply nested or mutually-recursive, like in a tree search, with plenty of c ...

Is it possible for TypeScript to mandate abstract constructor parameters?

This specific function is designed to take a constructor that requires a string argument and then outputs an instance of the constructed value T: function create<T>(constructor: new(value: string) => T): T { return new constructor("Hello& ...

What could be causing the primeng dialog to appear blank when conducting Jasmine tests on this Angular TypeScript application?

Having trouble testing a component due to rendering issues? Check out the code snippet below: import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core'; @Component({ selector: 'app-help', cha ...

How can I turn off strict null checks in TypeScript when using ESLint?

ESLint keeps flagging my object as potentially null despite having an if statement to check for it. const user: User | null = getUser() if (user) { // if (user !== null) doesn't work either await user.updateProfile({ di ...

Navigating with Angular: Transmitting dynamic URL parameters to components

I currently have the following routes defined: const routes: Routes = [ { path: ':product/new', children: [{ path: 'std/:country', component: SignUpComponent, data: { ...

What steps can be taken to skip the email verification in Auth0 when updating a password by confirming the old password?

I am in need of creating a personalized page for changing passwords using auth0. I want the process to involve directly modifying the password without requiring an email with a password change link. Additionally, it needs to have a feature for confirming t ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...