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

React development: How to define functional components with props as an array but have them recognized as an object

While trying to render <MyComponent {...docs} />, I encountered the following error: TypeError: docs.map is not a function Here's how I am rendering <MyComponent /> from a parent component based on a class: import * as React from &apo ...

Regex for US zip code with an optional format

Searching for a regular expression to validate US zip codes. I have come across multiple examples, but none of them cater to the scenario where the zip code is optional. The input field I am working on does not require a zip code, so it should accept a 5 ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

Issue with data not refreshing when using router push in NextJS version 13

I have implemented a delete user button on my user page (route: /users/[username]) which triggers the delete user API's route. After making this call, I use router.push('/users') to navigate back to the users list page. However, I notice tha ...

Utilizing Window function for local variable assignment

Currently, I am facing a challenge in my Angular2 service where I am attempting to integrate the LinkedIN javascript SDK provided by script linkedin. The functionality is working as expected for retrieving data from LinkedIN, however, I am encountering an ...

Adding an event listener to the DOM through a service

In the current method of adding a DOM event handler, it is common to utilize Renderer2.listen() for cases where it needs to be done outside of a template. This technique seamlessly integrates with Directives and Components. However, if this same process i ...

Ways to indicate a checkbox as selected within angular version 4

I'm a complete beginner in Angular 2 and I need to be able to check checkboxes when a button is clicked. I have multiple checkboxes generated in a loop like this: <tr *ngFor="let roleObj of roleNameList"> <td> <input ty ...

What is the method for extracting date of birth data from .NET to Angular?

Struggling to fetch the date of birth from the database where it has been stored. After searching through multiple resources online, I am still unsure about how to accomplish this task. export class DetailsEmployeeComponent implements OnInit{ employeeD ...

As I attempt to log in, the GitHub API is sending back a message stating that authentication

const fetchUser = async () =>{ let usernameValue : any = (document.getElementById('username') as HTMLInputElement).value; let passwordValue : any = (document.getElementById('password') as HTMLInputElement).value; const ...

Make sure to update the package.json file before initializing a fresh Angular application

As a newcomer to Angular, I'm currently following a tutorial that utilizes angular/cli version 8.3.6. I'm attempting to create a new app for an ASP.NET Core project, but I keep encountering dependency conflicts during the setup process. Running ...

Enhance Angular Material Select with Tooltip on Ellipsis Directive

In the midst of my Angular 9 project journey, I encountered a directive designed to add a matTooltip if an element's text is truncated (ending in ellipsis due to overflow). Everything was running smoothly with this directive until I introduced a mate ...

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

tsc is not recognizing the configurations in my tsconfig.json file

Running tsc in my project's directory is causing an error to be outputted (as shown below). This is my first attempt at using TypeScript and Node.js. Please consider me as a complete beginner. Operating system: Ubuntu 15.10 64bits NPM version: 2.4. ...

When trying to run the npm start command, an error occurs referencing type

I am facing difficulties running my project locally due to broken dependencies, and I'm struggling to find a solution. When attempting to install the node modules, I encountered errors, so I made changes to the following dependencies: "codelyze ...

Is error propagation from nested Promise to parent Promise not working properly in Node.js?

I'm currently working on a Node.js/TypeScript API with Express. Below is a snippet from my get method where I encountered an error in the format function. The error is caught by the promise, but it doesn't propagate to the parent promise after th ...

Return the reference to an injected service class from the location where it was implemented

Is it feasible to return a reference from a component class with a custom interface implemented to the injected service class in my Angular 6 project? Here is an example of what I am aiming for. ServiceClass @Injectable() export class MyService { co ...

SweetAlert2 not displaying properly in Ionic6 - troubleshooting the issue

My current project is an Ionic 5 Angular project with SweetAlerts2 popups. Recently, I decided to upgrade to Ionic6 and encountered an issue where the SweetAlerts2 popups are not displaying correctly. The alert seems to only show up in the header, leaving ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Encountering Typescript errors when trying to destructure a forEach loop from the output of

There are different types categorized based on mimetypes that I am currently working with. export type MimeType = 'image' | 'application' | 'text'; export type ApplicationMimeType = '.pdf' | '.zip'; expor ...