Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyup.enter), which does trigger the assigned function but causes issues with the patchValue() function. Here is a snippet of my code:

editor.component.ts

profileForm = this.fb.group({
    name: ['', Validators.required],
    address: this.fb.group({
             zip: ['', Validators.required],
             city: ['', Validators.required]})
             });

func(event: any){
  this.profileForm.patchValue({
      address:{
      city: this.getCity(event.value)
      }
    })  
}

getCity = (theCurrentZip: any) => {
  return Object.keys(this.zipCode).filter(z => {
    return this.zipCode[z].includes(theCurrentZip)
  })[0]
}

zipCode: any = {
  "A": ["1", "2"],
  "B":["3", "4"]
};

editor.component.html

<div>
<form (ngSubmit)="onSubmit()" #myForm="ngForm" class="profileForm">
<mat-form-field required>
  <input matInput id="name" placeholder="Contact Name" name="name" [(ngModel)]="name">
</mat-form-field >
<div formGroupName="address">
<mat-form-field>
    <input matInput id="zip" (keyup)="func($event.target)" placeholder="Zip" name="zip" [(ngModel)]="zip">
  </mat-form-field>
  <mat-form-field required>
    <input matInput id="city" placeholder="City" name="city" [(ngModel)]="city">
  </mat-form-field>
</div>
<p>
    <button type="submit" mat-raised-button color = "primary">Submit</button>
</p>
</form>
</div>

Answer №1

It seems that you are currently integrating both the reactive and template-driven approaches to Angular forms.

You have implemented the reactive approach in your editor.component.ts and the template-driven approach in your editor.component.html.

Since your HTML is using the template-driven approach, there is no need to use the patchValue method because the form and its controls are not directly connected to the HTML. Instead, you should update your implementation of the func function as shown below:

func(event) {
  this.city = this.getCity(event.target.value);
}

I recommend choosing one approach (either reactive or template-driven) and avoiding mixing them unless absolutely necessary. Additionally, consider using more descriptive function names than func ;)

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

Mapping strings bidirectionally in Typescript

I am currently working on a two-way string mapping implementation; const map = {} as MyMap; // need the correct type here const numbers = "0123456789abcdef" as const; const chars = "ghijklmnopqrstuv" as const; for (let i = 0; i < n ...

Creating Unique Identifiers in ExpressJS

I am currently utilizing mongoose to display admin and user information on a dashboard, but I am encountering difficulty rendering the id of a user. Below is the code I am using: function ensureAuthenticated(req, res, next){ if(req.isAuthenticated()){ ...

Error encountered in lodash.js in Angular 2 framework

I have been attempting to implement lodash for a datatable. Here are the steps I followed: First, I tried running npm install lodash, but encountered an error stating that the package could not be found After researching the issue, I attempted npm in ...

Incorporate Vuetify's v-stepper seamlessly with Vue router for dynamic functionality

Seeking assistance in integrating vuetify's v-stepper with vue router. Specific requirements include: Assigning each step its own route (e.g. /myform/step1, /myform/step2, /myform/step3, etc) Creating components for each step that are dynamically lo ...

Execute Angular within a designated directory

Can Angular be launched in a custom URL path like http://localhost:4200/abcde instead of just http://localhost:4200/? I have been unable to find any settings for changing the pathname. ...

Storing string variables within an array and subsequently evaluating the similarity of each variable's value with those stored within the array

I am currently working on an Angular page which consists of input fields where I capture and store values in variables within the .ts file. The entered values are subject to change, so hard-coding them is not feasible. The variables that I use for storing ...

Warning: Unhandled promise rejection - Type error encountered when trying to access property

While working on a simple login validation, I encountered an issue when deliberately inputting an incorrect email in the login post method via postman. UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of null at C:&b ...

Testing Angular 7 components: A guide to validating input element values

Upon updating an operational application from Angular 4 to Angular 7, I encountered a discrepancy. Consider the HTML Input below: <input id="encryptedValue" readonly class="form-control" [ngModel]="Response.encryptedText" size="50" /> Prior to the ...

switchMap: Triggering multiple requests simultaneously (2)

Currently, I am utilizing Angular 2 RC-4 and facing an issue where a network request is being triggered twice whenever there is a change in the input box. This is what my code looks like: component.ts this.term = new Control(); this.suggestions = this. ...

Utilizing Typescript in tandem with an external library through es6 modules

Is there a recommended method for incorporating Typescript with non-module libraries like PixiJS and SortableJS without using webpacker? I'm looking to utilize es6 modules but want to avoid cumbersome solutions. What would be the best approach in this ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

Using jQuery's append function will retrieve external source files within script tags, however, it will not officially render them in the DOM

After including a script with an external source and attempting to parse it using jQuery, the script is downloaded but not loaded into the DOM. This issue persists regardless of which jQuery DOM insertion method I use, such as .append(). Take a look at th ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...

How to extract information for divs with specific attribute values using Jquery

I have multiple divs with IDs like #result-1, #result-2, each followed by a prefix number. To count the number of list items within these divs, I use the following code: $(document).ready(function () { var colorCount = $('#result-1 .item-result ...

Beware of UTF-8 Decoding Problems: Avoid using "0"-prefixed octal literals and octal escape sequences as they are outdated. For octal literals, opt for the "0o" prefix

I've hit a roadblock trying to achieve this task, any assistance would be greatly appreciated. I have a string that looks like this "jas\303\241nek" and I need to convert it to look like "jasánek". After using [this web ...

Using Jquery to make an Ajax request to a PHP script that retrieves JSON data

Hello, I am new to working with JSON. I have a PHP script that contains a multidimensional array, which is then encoded into JSON format like this: <?php header('Content-Type: application/json'); $lista = array ( 'Conoscenti'=&g ...

Example of Signature in TypeScript Function Declaration

While going through this documentation, I found myself puzzled by the concept of having a parameter that can be both an object and a function in JavaScript. type DescribableFunction = { description: string; (a: any): boolean; }; function doSomething( ...

Unable to extract query parameters from URL using Express JS as req.query returns an empty object

I came across discussions about this issue here and here, but unfortunately, the solutions provided didn't work for me. I'm attempting to extract parameters from the URL using req.query. In my server.js file, I've implemented the following: ...

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...

What is the purpose of including an express server instance as an argument for the http module in Node.JS?

Currently delving into the realms of Node.JS, Express.JS, and Socket.IO. The tutorials I've come across so far showcase a complex series of code to kickstart each of these modules: var express = require("express"); var app = express(); var server = ...