Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utilizing a single function that can be customized through passing in the text field ID.

Here is an example of what I have now in HTML:

<div class="col-sm-4">
     <input type="text" class="form-control" id="textField1" formControlName="textField1" />
</div>
      <button class="btn btn-danger" (click)="clearTextField('textField1')"><i class="fa fa-times"></i></button>

As shown above, I have a specific function for each text field like "clearTextField1()". Is there a way to achieve the desired outcome with just one function and dynamically pass in the text field ID when needed?

Answer №1

To make it work, simply include the formcontrolname in the click functions.

  <button class="btn btn-danger" (click)="clearTextField1('textField1')"><i class="fa fa-times"></i></button>

Here is the function that should be used:

clearTextField1(field:String): void {
    return this.form.controls[field].setValue('');
}

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

Accessing React.FC in Another File with TypeScript - A Step-by-Step Guide

code - const Exne: React.FC <IProps> = ({x}) => { console.log('input', x); const [getx, assignx] = useState(x); console.log(getx, assignx); return(getx) }; Could you please provide instructions on how to acc ...

Could Angular2's Http Get method exclusively handle Json data?

mma-api.service.ts getAthletes() { return this.http.get('http://mma-data-api.mma.com/api/v3/athletes') .map(res => res.json()); } athlete.component.ts data: string; constructor(private mmaApiService: MmaApiService) ...

Invoking a nested class while declaring types in TypeScript

This is the specific format of data that I am in need of this.structure=[ { id: 1, name: 'root1', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { ...

Struggling with aligning mat-icon in the center using HTML and CSS?

My issue is that the mat-icon in my generated columns is not center aligned. What could be causing this? When using ngFor to generate my datatable columns dynamically, none of them align correctly. The mat-icon inside my DIV defaults to left alignment. ...

Concealing the Submit Button During Server Processing (Issues with Binding?)

My Angular 2 form is set up to send data to the server asynchronously. I want to provide users with visual feedback during the waiting period by changing the blue 'submit' button to a greyed-out 'Please wait...' button. To achieve this, ...

What is the correct way to set up child page routes with query parameters in the app-routing.module.ts file for Angular?

const routes: Routes = [ { path: '', component: DraftAnalysisHomeComponent }, { path: 'nfldraftanalysis', component: DraftAnalysisHomeComponent }, { path: 'nfldraftanalysis/averagegrades', component: AverageGrade ...

Button to expand or collapse all sections in Ant Design Collapse component

Is there a way to create a button that can expand or collapse all tabs in an ant.design Collapse component? I attempted to modify defaultActiveKey but it seems like this can only be done during page rendering. If possible, could someone share a code snip ...

I've tried using a ControlValueAccessor, but for some reason the value isn't getting passed to the form

Currently, I am experimenting with reactive forms in Angular, and I'm encountering difficulties with updating the form from custom components. As an example, take a look at the date-input component created using flatpickr in the linked Plunker demo. ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

Closures are like the "use" keyword in PHP or the capture list in C++, but they play a similar role in JavaScript and other transpiler languages

PHP has a useful feature with the use keyword, which allows for the usage of 'external' variables in closures. For example: $tax = 10; $totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use' return ($price * $quan ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...

Invoke a method in a child component from its parent component

Is there a way to trigger a function on a child component from the parent component? In my scenario, I have a ModalComponent (parent) and a MessageComponent (child), and I need them to communicate. In Angular 1, this was achievable through a shared service ...

Mastering the Art of Utilizing Generic Typing to Access Objects

I am trying to find a way to access an object by class using generic typing. The issue I am encountering is that I am getting an error when trying to check if the locators contain an input field. type '{ form1: { item2: { checkbox: string; input: st ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...

Maintain the URL state while logging in using angular-oauth2-oidc

In our Angular application, we utilize angular-oauth2-oidc for authentication management with the Code Flow and PKCE. To enable automatic login for users upon app visit, we initialize our app as follows: this.oauthService.configure(authModuleObject); this. ...

I'm struggling to set up break points in both my Angular application and library within VSCode. I can only seem to get them working in either one or the other, but not both

My goal is to enable debugging in vscode for both my Angular 16 application and my library at the same time. The file structure looks like this: ./root ./root/my-app/src ./root/lib/projects/my-lib I have successfully added my lib to the app's pr ...

Mongoose does not compare BCRYPT passwords that are empty

I'm currently working on incorporating bcrypt into my mongoose model using typescript. Referencing this link as a guide. However, since my project is in typescript, I'm unable to directly use the provided code. I'm confused about how they&a ...

Determine the implicit type of the assigned function, while also constraining the return type to be a subtype of a predefined

When writing multiple functions for server requests, I have encountered a dilemma with TypeScript. Each function must return a type that extends a specific predefined known type, but I also want TypeScript to infer the most accurate return type possible. ...

Generating a d.ts file for images in Typescript using automation techniques

Currently, I am working on a React application that utilizes TypeScript and webpack. I am aware that in TypeScript, when importing an image file, it is necessary to create a d.ts file in the current directory and include the following code: // index.d.ts ...