Is there a way to disable a button and have it also clear the value upon clicking?

Is there anyone who can assist me? I am looking for help to modify the following code so that...

  1. The button should only be clickable when the username field is not empty.

  2. Clicking on the button should clear the username input.

Below is the code snippet:

username.html

    <section class="username">

    <input
    type="text"
    class="form-control"
    (input)="onUpdateUsername($event)">


    <button class="btn btn-primary"
    [disabled] = "!allowNewUsername"
    (click)="onCreateUsername();">Add Username</button>

    <p class="test"> {{ usernameCreationStatus }} </p>
    </section>

username.component.ts

    export class UsernameCheckComponent implements OnInit {
    allowNewUsername:boolean = false;
    usernameCreationStatus = 'Nothing was created!';
    userName = 'TestUsername';

    constructor() {
    setTimeout(() => {
    this.allowNewUsername = true;
     }, 2000);
    }

    ngOnInit(): void {
    }

    onCreateUsername () {
    this.CreationStatus = 'Username was created! Username name is ' + this.serverName;
    }

    onUpdateUserName(event:Event) {
    this.userName = (<HTMLInputElement>event.target).value;
     }
    }

Answer №1

To prevent users from adding a new username, you can simply disable the button when the username field is empty or when the allowNewUsername option is set to false.

<button class="btn btn-primary"
    [disabled] ="!userName || !allowNewUsername"
    (click)="onCreateUsername();">Add Username</button>

In your component class, remember to reset the userName variable after creating the username.

onCreateUsername () {
    this.CreationStatus = 'Username was created! Username name is ' + this.serverName;
    this.userName = ''; // reset the username
}

Answer №2

If you want to check the validity of a button, you can create a getter for it:

export class UsernameCheckComponent {
    public usernameCreationStatus: string = 'No usernames created yet!';
    public userName: string | null = null;
    public get allowNewUsername() { return this.userName?.length }

    constructor() { }

    public onCreateUsername () {
        this.usernameCreationStatus = `A new username has been created! Username is ${this.serverName}`;
    }
}

In your HTML template, you can use the following code:

<section class="username">
    <input type="text"
        class="form-control"
        [(ngModel)]="userName">

    <button class="btn btn-primary"
        [disabled] = "!allowNewUsername"
        (click)="onCreateUsername()">Add Username</button>

    <p class="test"> {{ usernameCreationStatus }} </p>
</section>

Answer №3

To enable two-way binding for input fields, consider using ngModel. This allows you to access the variable value in both the template and view.

component.html

<section class="username">
  <input type="text" class="form-control" [(ngModel)]="userName" (input)="onUpdateUsername($event)">
  <button class="btn btn-primary" [disabled] = "userName != ''" (click)="onCreateUsername();">Add Username</button>
  <p class="test"> {{ usernameCreationStatus }} </p>
</section>

component.ts

onUpdateUserName(event: Event) {
   this.CreationStatus = 'Username was created! Username name is ' + this.serverName;
   this.userName = "";
}

Answer №4

When setting up the app.module.ts file:

import { ReactiveFormsModule } from "@angular/forms";

For the username.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';


@Component({
  selector: 'app-username',
  templateUrl: './username.component.html',
  styleUrls: ['./username.component.css']
})
export class UsernameComponent implements OnInit {

  constructor(private fb: FormBuilder) { }

  form!: FormGroup;
  usernameEntered!: string;

  ngOnInit(): void {
    this.form = this.fb.group({
      username: this.fb.control('')
    })
  }

  onSubmit(data: any){
    console.log(data); //any function
    this.form.reset(); 
    this.usernameEntered = ''; 
  }

  userInput(data: string){
    this.usernameEntered = data; 
  }


}

In the username.component.html file:

<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
    <input #userInputId 
            formControlName="username" 
            type="text" 
            placeholder="username" 
            (input)="userInput(userInputId.value)"> 
    <button type="submit" [disabled]="!usernameEntered">Submit</button>
</form>

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

Exploring Angular: A Guide to Localisation and JSON

Looking at my JSON database structure below: { "users" : { "-Kowtg5yyK-DTIz91cQ8" : { "language" : "en", "uid" : "kNyDJnktxyakL6owhGd1rruGACb2", "userName" : "admin" } }, "localisation" : { "login" : { "en" : "Log ...

The MaterialModule export could not be located

After installing the Angular Material Library, I encountered a Module not found error. Can anyone provide a solution for this issue? Thank you. material-module.ts import { NgModule } from '@angular/core'; import { A11yModule } from '@angula ...

What is the best way to switch on/off data loading from the server with a click

I have a button with a click event that sends a server request each time it is clicked. The request should only be sent when the condition showVersions is true. The functionality of the button historyBtn should act as a toggle. This has been my attempt: ...

Differentiating between TypeScript string literal types and enums

Is it better to use enum or string literal type in TypeScript? String literal type: export type Animal = { id : number, name : string, type : "dog" | "cat" } Enum: export enum Type{ dog = "dog", cat = &qu ...

Enhancing TypeScript functionality by enforcing dynamic key usage

Is there a way to ensure specific keys in objects using TypeScript? I am attempting to define a type that mandates objects to have keys prefixed with a specific domain text, such as 'create' and 'update': const productRepoA: Repo = { } ...

Ways to repurpose Angular modules for different projects

I am looking to distribute a custom Angular 2 module within other projects in my company. For instance: @NgModule({ declarations: [ AppComponent, BannerInlineComponent, WelcomeComponent ], imports: [ BrowserModule, FormsModule ...

Discover the method for extracting a value from an interface and incorporating it into a separate function

I need help accessing the value of userType for a conditional statement. UserType: const RadioForm = (props) => { return ( <div> <label>Customer</label> <input type="radio&qu ...

Task ':processDebugGoogleServices' could not be added because there is already a task with the same name

Trying to test out the firebase FCM plugin, but encountering numerous errors along the way. After resolving most of them, I attempted to perform the following command: ionic cordova build android, only to be faced with the following error: Here's wha ...

How can you load a chosen list in Angular's Mat Selection List component?

I populated my selection list with a list of items. How can I specify which item should be selected in the list after it has been loaded? Here is the HTML code snippet: <div class="col-md"> <div class="form-group"> ...

Querying Angular/Firestore for a collection document to extract a single field from each document and store them in an array

I am currently querying my collection of documents and attempting to extract only the phone numbers into an array. The goal is to store the phone numbers in an array for use by another function. While the Firebase documentation provides examples using co ...

Type inference error in TypeScript occurs within a conditional statement when the condition relies on the output of a function call rather than a boolean expression

In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list. type ListItem = number | string | object; class Node { private value: ListItem; private next: Node | nu ...

Exploring Elements of Ionic 4

My component utilizes both a static and dynamic class, where the dynamic class is only added under certain conditions. While my current implementation works fine, I feel it may not be the most elegant solution. How would you approach this? I am particula ...

Utilizing PrimeNG Datatable to Connect with an Array of Objects in a Dynamic Manner

I currently have an array of objects with various properties such as: "rows": [ { "id": 1, "createdAt": "2017-07-21T06:05:38.000Z", "updatedAt": "2017-07-21T06:05:38.000Z", "createdBy": null, "modifiedBy": null, "name": "ABC", "owner": "Dian ...

The element's type is implicitly set to 'any' as the expression of type 'string' is unable to index the 'PointDto' type

Comparing the values of x1, y1 and z1 in PointDto objects (point1 and point2) Example :- point1 => PointDto: { x1: "1.000000", y1: "1.0", z1: undefined pointIndex: 0, } point2 =& ...

How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items. For example: employees: any; offices: any; constructor() { this.employees = [ { fname: "John", lname: "James", sta ...

Function in Typescript used for checking types and catching compilation errors from external sources

Fact: I am currently using TS version 2.3.4. I have developed a function that checks if a variable is defined (it takes the parameter variable and returns 'undefined' !== typeof variable). It's quite simple. export function IsDefined(variab ...

You cannot assign the "unknown" type to the "boolean" type

if (queueEntry) { this.inProcess.push(queueEntry); try { await callback(queueEntry); this.inProcess = this.inProcess.filter(queueTmp => queueTmp.id !== queueEntry.id).concat([]); th ...

Issue encountered when utilizing TypeORM within NestJS: Unable to import Entity Repository

Issue with EntityRepository Import Despite having @nestjs/typeorm installed, VS Code is not recognizing the decorator I need to use. Any suggestions on how to resolve this? ...

Is there a way to determine the height of the ion-footer?

Is there a way to obtain the height of the ion-footer element in Ionic2? I want to calculate the initial window height minus the ion-footer height, but I am currently only able to get the overall window height. I'm not interested in retrieving the ...

Navigating Promises in Node.js: Best Practices

Seeking help with executing a callback function in nodejs using expressjs and angular 2. My process involves sending a form data to an API route, querying a MYSQL database for user details, and expecting to receive the complete user information from the ph ...