Tips for clearing the text field upon clicking the "clear" button in an Angular 8 template-driven form

I'm currently working on creating a simple login form with two input fields and a "clear" button that should clear the input field when clicked. How can I achieve this?

I understand how to reset the form in reactive forms using reset(), but I am unsure of how to do it in a template-driven form.

<form>
  <label>Username:</label>
  <input   name="username" ngModel #name="ngModel" required minlength="4" maxlength="10" appForbiddenName="jedii" type="text">
   <div *ngIf="name.touched && !name.valid">
     <div *ngIf="name.errors.required">Username is mandatory</div>
     <div *ngIf="name.errors.minlength">Username must be at least 4 characters</div>
     <div *ngIf="name.errors.forbiddenName">Username cannot be jedii</div>
   </div> 
  <br><br>
  <label>Password:</label>
  <input type="password" required>
</form>
<br>
<button>Login</button>
<br>
<br>
<button>Clear</button> 

My expectation is that the text field will reset to blank, but nothing happens when I try.

Answer №1

In situations as straightforward as this one, you have the option of utilizing type=reset

<form>
    <input type="text"><br>
    <input type="password"><br>
    <button type="reset">Clear</button><br>
    <button type="submit">Login</button>
</form>

Answer №2

If you want to clear a form in Angular, you can use the ngForm attribute.

Click here for a guide on how to use ngForm

Here is an example:

<form #testForm="ngForm">
</form>
<button (click)="testForm.reset()">Clear</button>

Edit: It should be resetForm(). Make sure to check the guide for more information. Thank you.

Edit: Here is the final solution

<form #testForm="ngForm">
        <label>Username:</label>
        <input name="username"
               ngModel
               #name="ngModel"
               required
               minlength="4"
               maxlength="10"
               type="text">

        <br><br>
        <label>Password:</label>
        <input type="password"
               ngModel
               name="password"
               #password="ngModel"
               required>
      </form>
      <br>
      <button>Login</button>
      <br>
      <br>
      <button (click)="testForm.resetForm()">Clear</button>

Answer №3

Utilize the form template reference as shown below:

<form (ngSubmit)="onSubmit(login)" #login="ngForm">

In your .ts file, implement it like this:

onSubmit(login: ngForm) {
  login.resetForm();
} 

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

Is there a way to display a message box when the mouse cursor hovers over a text box?

Currently, I have set up 3 text boxes in my project. The functionality I am trying to achieve is when the user clicks on the second text box, the value of the first text box should be displayed in a message box (providing that the validation for the first ...

What is the reason for the undefined status of my variable "j"?

I am working on coloring my 3D object using Three.js. I have a variable called j. When I use alert(j), it works fine. However, when I try to use the variable as an index in my array (colormap), it doesn't work. colormap=[[0,0,0.5625],[0,0,0.625],[0,0 ...

Masking credit card numbers in an Asp.net text box upon entry, validating the input, and securely processing the credit card information

I am currently maintaining an Asp.Net web application that deals with processing credit card payments. However, in order to comply with new regulations, I am required to mask the credit card number as it is being entered. For example, if the first number e ...

Prevent submission by deactivating the button if a file has not been

I need help implementing a solution to disable a submit button until a file is selected. I found a working example online, but I'm not sure if the issue lies with the script type. Here's the example I'm referring to: disable submit button u ...

Creating a top-to-bottom pull effect on a single page, similar to the Android title bar, can be achieved using CSS3

Is there a way to achieve an effect in HTML that resembles the pull title bar animation from top to bottom in Android? Any suggestions on how to create this effect or what tools I would need? Currently, when I swipe, the page simply displays a following ...

Issue encountered while attempting to access webpage using Node.js and Express

Currently, I am in the process of creating a web page using nodejs express and mongodb. I found some code on this GitHub page that I have been studying. However, I encountered an error when attempting to view the web page. The issue arises when I uncommen ...

Is there a way to ensure that a popup is scaled in proportion to its content?

Is there a way to make external links open in a new window with a size relative to the parent window, making it clear to the user? I initially used the target attribute but found a workaround like this: <a href="http://example.org" onclick="window.op ...

Encountering a ValueError when attempting to validate form fields with Django and JavaScript

I encountered an error while trying to validate a field using Javascript and Django. Error: ValueError at /insert/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/insert/ Django Version: ...

Enter your own text into the input fields to create a personalized message

Is there a way to eliminate duplicates when checking the checkboxes? <label><input type="checkbox" data-bValue="100" data-sValue="sV1" data-nValue="nV1" name="layers"> 100</label><label><input type="checkbox" data-bValue="200" d ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...

specialized html elements within data-ng-options

I have a code snippet where I am populating select options from a controller using data-ng-options. However, I would also like to include an icon with each option. For example, I want to append <span class="fa fa-plus"></span> at the end of e ...

Exporting data to CSV using PrimeNG

Utilizing a PrimeNG grid, the data being retrieved from a service is paginated on the server side. This means that only the current page's data is received at a time. The relevant HTML code is displayed below: <p-dataTable *ngIf="displayTable" # ...

iisnode ran into a problem while handling the request. Error code: 0x6d HTTP status code: 500 HTTP subStatus code: 1013

Currently, I am working on a web application using ReactJS for the frontend and Express for the backend. My deployment platform is Azure. In order to verify that my requests are being processed correctly, I decided to conduct two API tests. The first tes ...

Issue with resizing causing layout glitches in jsPanel

Greetings and I hope you're enjoying your weekend! I just started working with jsPanel and I've encountered a small issue. Whenever I try to resize the panel, the layout glitches. The shadow disappears and the header becomes abnormally large. I& ...

Attempting to implement Angular for routing but encountering a 'Cannot GET /[something]' error with my NodeJS Server

Currently, I have set up NodeJS/ExpressJS as my server but I am looking to utilize Angular 7 for routing purposes. I have configured the Angular routing script successfully, as evidenced by the login component loading when the path is set to ''. ...

Ways to delete the title from a box in orgChart

Is there a way to remove the title from the box and only show the content? I've searched extensively but haven't found a solution yet. I'm currently using orgChart: https://github.com/dabeng/OrgChart For example, the general manager box s ...

"Angular form's controls are valid but the form itself is marked

When creating a form group with existing values: this.form = new FormGroup({ field1: new FormControl( { value: obj ? obj.value : null, disabled: obj }, Validators.required ), field2: new FormControl( { value: obj ? ...

Angular reloads content when language is switched

I am facing an issue with my language selector and default pipes for number or currency format. Even after changing the language (e.g., from en-US to fr-FR), the thousands separator remains unchanged despite the correct updates in LOCALE_ID and TranslateSe ...

What is the Reactjs method for relocating a button from one div to another upon being clicked?

I have organized the buttons inside a div like this: const [state, setstate] = useState([]); getButtonsUsingMap(){ const arr = [1,2,3,4,5]; return arr.map((num) => { return ( <button key={num} className="bu ...

How can we solve the issue of missing props validation for the Component and pageProps in _app.js?

Below is the code snippet from _app.js for a nextjs project that uses typescript import React from 'react' import '../styles/globals.css' function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } export ...