Guide to Angular 6 Reactive Forms: Automatically filling one text field when another input is selected

I'm currently learning Angular 6 and exploring reactive forms. I want to set up a feature where selecting an option in one field will automatically populate another field.

The objective is to have the coefficient input update based on the number selected from the dropdown menu. For instance, choosing '1' should set the coefficient to ".15". Similarly, selecting '2' should correspond to ".175", and '3' to ".2".

What would be the most effective approach to implement this functionality? Thank you for your assistance!

Below is my form setup:

<form name="form" class="form-horizontal" (ngSubmit)="createForm.form.valid && createNewMonitoringPoint()" #createForm="ngForm" novalidate>

 <select class="col-md-12 form-control" [(ngModel)]="newmp.number"
    [ngClass]="{ 'is-invalid': createForm.submitted && newmp.number.invalid }" 
    required name="number">

    <option value="" disabled selected>Choose...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>

 </select>

 <p>Pipe Roughness Coefficient (n) </p>
 <input type="coefficient" id="coefficient" 
    #coeffcient="ngModel" name="coefficient" [(ngModel)]="newmp.coefficient" 
    class="form-control" placeholder="e.g. .016" />

 <button type="submit" value="Create">Create</button>

</form>

Answer №1

Utilize a template form instead of a reactive form. Insert the (change) method within the select form like so:

<select (change)="selected()">...</select>

Here is the logic:

selected() {
  if (this.newmp.number === 1) {
    this.newmp.coefficient = .15;
  } else if (this.newmp.number === 2) {
    this.newmp.coefficient = .175;
  } else if (this.newmp.number === 3) {
    this.newmp.coefficient = .2;
  }
}

Explanation: The implementation involves using two-way data binding with inputs through [(ngModel)]. Any changes in the model will update the input value and vice versa. When there is a change in the select element, the change() event is triggered which then calls the method select() or any desired name. No need to pass values explicitly as

this.newmp.number</code contains the updated value. As you perform your logic and assign the value to your input via <code>this.newmp.coefficient
, the updated value automatically reflects in the HTML template due to two-way data binding.

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

In Javascript, determine the root cause of a boolean expression failing by logging the culprit

Within my JavaScript code, I have a complex predicate that comprises of multiple tests chained together against a value. I am looking for a way to log the specific location in the expression where it fails, if it does fail. Similar to how testing librarie ...

How can I enable autofocus on a matInput element when clicking in Angular 6?

Is there a way to set focus on an input element after a click event, similar to how it works on the Google Login page? I've tried using @ViewChild('id') and document.getElementId('id'), but it always returns null or undefined. How ...

Encountering issues with Angular component test cases: receiving a Type Error stating it cannot read the property "contractno" as it is undefined

When attempting to inject the default dependency required to run the spec file without errors, I encountered a Type Error: Cannot read property "contractno" of undefined. /** This is the userModel Class **/ export class UserModel { contractNo: string; ...

Create a separate variable for every component within a custom module in Angular 4

In my Angular 5 project, I have a custom module called "Restaurant." The "Restaurant" module includes 5 components: Banner, Menu, Recommend, Basket, and Restaurantlayout. Restaurantlayout contains all the other components (Banner, Menu, Recommend, Basket ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

You are able to set up the booking.com form once but cannot do so again using the ngOnInit method

Currently, I am utilizing angular materials in conjunction with angular4. Within an MdDialogue component, I have embedded HTML code for a booking.com form. The intention is for this dialogue box to appear with the form inside whenever a button is clicked. ...

[Vue warning]: The property "text" was accessed during rendering, however it is not defined on the current instance using Pug

Looking for some guidance from the Vue experts out there. I've recently started working with Vue and I'm attempting to create a view that verifies an email with a unique code after a user signs up. Right now, my view is set up but it's not c ...

Issue Establishing Connection Between Skill and Virtual Assistant Via Botskills Connect

Encountering errors while connecting a sample skill to a virtual assistant. Both are in typescript and function individually, but when using botskills connect, the following errors occur: Initially, ran botskills connect with the --localManifest parameter ...

Exploring the depths of complex objects with the inclusion of optional parameters

I've been working on a custom object mapping function, but I've encountered an issue. I'm trying to preserve optional parameters as well. export declare type DeepMap<Values, T> = { [K in keyof Values]: Values[K] extends an ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

Implement a personalized Laravel Dusk selector with the attribute data-dusk

In the world of Laravel Dusk, the default selector hunts for the dusk="something" attribute in your HTML. If you want to dive deeper into this topic, check out this resource. However, when it comes to compatibility with Typescript for React/Vue, ...

Troubleshooting: Issues when using jQuery metisMenu in conjunction with *ngIf

We are facing an issue while using the metisMenu with Angular2. There is an *ngIf condition on one of the list items, and its visibility changes based on whether a record is selected. When the li item is shown for additional options, it does not work prope ...

Struggling with defining content and background scripts while using AngularJS2 CLI to build a Chrome extension

After creating a brand new AngularJS-2 application using the cli tool from github, I discovered that running ng build compiles my sources into a /dist folder. As I am developing a chrome extension, I need to specify the location of my content script (whi ...

What is the best way to set up initial state in react-native-day-picker?

I have been experimenting with implementing react-native-calendar into my project. Here is the code snippet I am working on: import React from 'react'; import {Calendar} from 'react-native-day-picker'; const MyCalendar = () => { ...

Best Method for Confirming Deletion in Data Table with Shadow and UI

I have a query regarding the Shadcn/UI - Data Table component. In my case, I am working with a list of users where each row has a delete button in the last column. Upon clicking the delete button, a confirmation dialog pops up. Currently, I am implementi ...

Angular4 interceptor modifying the response

I've implemented an HttpInterceptor: import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; import {AuthService} from '../service/auth.service'; import {Observable} from &apo ...

Can parameters with identical union types in a function signature be streamlined to contain only the exact same subtypes using generic types?

// defining a type Combinable with string or number as possible values type Combinable = string | number; // function to check if parameter is a string function isString(param: unknown): param is string { return typeof param === "string"; } /** * Func ...

Iterate through elements in Angular using *ngFor with a TrackBy function across two levels of nested

I am currently dealing with 2 nested loops in my code, set up like this: <div *ngFor="let page of pages; trackBy: trackByPageId" class="page"> <app-item-component *ngFor="let item of page; trackBy: trackByItemID" ...

What could be causing the observable collection to display the correct number of objects, yet have them all appear empty?

I am offering the following service @Injectable() export class LMSVideoResulful { getVideos( enrolmentId : number ) :Observable<Array<Video>> { var x = new Array<Video>(); //https://www.youtube.com/embed/MV0vLcY65 ...

Is it possible to import the identical file twice consecutively using html and typescript?

I encountered an issue with an input element in my HTML file. Here's what it looks like: <input type="file" (change)="receiveFile($event)" id="inputFileButton" hidden /> This input element is designed for users to import files. Wh ...