What is the best way to enforce input requirements in Typescript?

I am currently facing an issue with two required inputs that need to be filled in order to enable the "Add" button functionality. I have considered using *ngIf to control the visibility of the button based on input values, but it seems to not be working. Can anyone point me in the right direction?

<input
    #neueEintragBeschreibung
    placeholder="Enter description"
    class="lg-text-input"
  />

  <input
    #neuesEintragFaelligkeitsdatum
    placeholder="Enter due date"
    class="lg-text-input"
  />

  <div *ngIf="neueEintragBeschreibung.value">
  <button class="btn-primary" (click)="addEintrag(neueEintragBeschreibung.value, neuesEintragFaelligkeitsdatum.value)">
    Add</button>
  </div>

Answer №1

If you want to retrieve the value of an input, it's best practice to utilize the forms API instead of directly accessing input.value. Here's an example:

<form #form="ngForm" (ngSubmit)="handleSubmit(form)">
  <input type="text" required name="myField" ngModel />

  <ng-container *ngIf="form.valid">
    <button type="submit">Add</button>
  </ng-container>
</form>
handleSubmit(form: NgForm) {
  console.log(`You entered: ${form.value.myField}`);
}

In this code snippet:

  1. A form is created with a single field named "myField".
  2. The field "myField" is made mandatory by utilizing the required attribute.
  3. The "Add" button is only displayed when the form is valid. As the form mandates a required field, it will be considered valid once the user fills in this field.

Don't forget to include FormsModule in your module's imports for this functionality.

Answer №2

To discover the solution, visit this link: https://www.digitalocean.com/community/tutorials/angular-reactive-forms-introduction

stackblitz:*https://stackblitz.com/edit/angular-ivy-im2nap?*file=src/app/app.module.ts

Utilize Angular Forms and denote the field as mandatory using a validator rule:

HTML

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
  <div>
    <label>
      Name:
      <input formControlName="name" placeholder="Your name">
    </label>
    <div *ngIf="myForm.get('name').invalid && (myForm.get('name').dirty || myForm.get('name').touched)">
      Please provide a name.
    </div>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Send</button>
</form>

In your component, ensure to import the following:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

Additionally:

myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      name: ['Sammy', Validators.required],
    });
  }

  onSubmit(form: FormGroup) {
    console.log('Valid?', form.valid); // true or false
    console.log('Name', form.value.name);
  }

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

Error encountered while exporting TypeScript module

While I am working with Angular, TypeScript, and Gulp, my module system is CommonJS. However, I encountered an error when trying to import a module into my main.ts file: Error: Cannot find external module 'modules.ts'. Here is the snippet from ...

How to update path parameters in Angular 2 without triggering a redirect

Is there a way to update the URL Path in Angular 2 without actually redirecting the page? I am familiar with accessing query parameters using ActivatedRoute's queryParamMap Observable, but how can I change these values and have them reflected in the ...

Include token in src tag requests Angular version 8

In the process of developing a website, I have encountered a challenge. I am creating a platform where users can access another website I am currently working on after they log in. Once authorized, users receive a JWT token which is sent in the header with ...

Understanding the appropriate roles and attributes in HTML for a modal backdrop element in a TypeScript React project

Trying to create a Modal component using React and TypeScript with a feature that allows closing by clicking outside. This is being achieved by adding a backdrop element, a greyed out HTML div with an onClick event calling the onClose method. Encountering ...

Leveraging uninitialized data in Angular

<ul class="todo-list"> <li *ngFor="let todo of todos" [ngClass]="{completed: todo.isDone, editing: todo.editing}" > <div class="view"> <input class="toggle" type="checkbox" [checked]="tod ...

Utilizing Dynamic Components and the Event Emitter Feature in Angular Version 5

As a newcomer to Angular, I am currently grappling with the concept of dynamic components within my project. Specifically, I am working on implementing functionality where a user can select a row in a component and then click a button to open a modal (cont ...

Encountering the error message "Received 1 argument, when expecting 4" while attempting to utilize a vuex getter in TypeScript

I encountered an issue while unit testing a getter function. The error message Expected 4 arguments, but got 1. appeared when I attempted to use the getter. My application was built using Quasar and utilizes TypeScript. The value of HttpMocks.mockToken is ...

What is the best way to handle a global path parameter in a Nest.js application?

Currently, I am in the process of constructing a rest API for a fully multi-tenant system using a single database and application. To achieve this, I have chosen NestJS as my framework of choice. My goal is to structure all modules based on the :tenantID t ...

Elementary component placed in a single line

Creating a text dropdown menu using the following code: import { Autocomplete, TextField } from '@mui/material' import React, { useState } from 'react' const options = [ 'Never', 'Every Minute', 'Every 2 ...

Angular Dynamic CSS Library by BPNM

I'm currently working with the Bpmn library to create a diagram. However, I've encountered an issue where I need to hide the palette in the diagram view dynamically. I attempted to achieve this by using @ViewChild in my TypeScript file to target ...

What could be causing the Timeout error to occur in my Jasmine unit test for the HTTP interceptor?

I've been facing challenges with unit testing my interceptor since yesterday afternoon. Despite following multiple tutorials and Stack Overflow answers, I have managed to write what seems like the best code so far. However, I'm encountering an er ...

Received corrupted file during blob download in Angular 7

When using Angular 7, I am making an API call by posting the URL file and attempting to download it using the 'saveAs' function from the fileSaver library. The file is successfully downloading, but it appears to be corrupted and cannot be opened. ...

Angular - Leveraging Jest and NgMocks to Mock Wrapper Components

Within our project, we have implemented a feature where user roles can be assigned to various elements in the application. These roles determine whether certain elements should be disabled or not. However, due to additional conditions that may also disable ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...

Initiate the input change event manually

Struggling with creating a custom counter input component where the input value is controlled by custom increment/decrement buttons. Desired output: https://i.sstatic.net/oYl1g.png Content projection will be used to expose the input for form usage and a ...

Angular 8: Syncing Component Values with Service Updates

My Angular 8 project features two sibling components that utilize a service to manage restaurant data. One component displays a list of restaurants fetched from an api, while the other component filters the displayed restaurants based on user input. Despit ...

Using TypeORM's QueryBuilder to select a random record with a nested relation

Imagine a scenario where I have the following entities: User @Entity('user', { synchronize: true }) export class UserEntity { @PrimaryGeneratedColumn('uuid') id: string; @Column() firstName: string; @Column() lastName: s ...

Utilizing Angular's DomSanitizer to safely bypass security scripts

Exploring the capabilities of Angular's bypassSecurityTrust* functions has been a recent focus of mine. My objective is to have a script tag successfully execute on the current page. However, I keep encountering issues where the content gets sanitized ...

Google Chrome - Automatically scroll to the bottom of the list when new elements are added in *ngFor loop

I have a basic webpage showcasing a list of videos. Towards the bottom of the page, there is a button labeled "Load more". When a user clicks on this button, an HTTP request is triggered to add more data to the existing array of videos. Here is a simplifi ...

Can Angular access a JSON file post-build?

Currently, I am developing an Angular 7 project that has to be deployed on various servers. One of the requirements is to retrieve the server URL from an environment file rather than hardcoding it as a static variable. I attempted to read the information ...