Home > Software design >  How do I make an Input required in Typescript?
How do I make an Input required in Typescript?

Time:09-16

I have two Inputs, that have to be required, in order to use the "Add"-Button or I was thinking to use *ngIf to make the button visible or not, but it doesnt work. Whats wrong?

<input
    #neueEintragBeschreibung
    placeholder="Eintrag hinzufügen"
    
  />

  <input
    #neuesEintragFaelligkeitsdatum
    placeholder="Faelligkeitsdatum hinzufügen"
    
  />

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

CodePudding user response:

You're not supposed to access input.value this way. You should use the forms API to do so. E.g:

<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}`);
}

What's happening here:

  1. You create a form with one field, called "myField".
  2. You make "myField" required by using the required attribute.
  3. You render the "Add" button only when the form is valid. Since the form has a required field, it will only be valid once this field is filled by the user.

Remember to add FormsModule to your module's imports.

CodePudding user response:

You can find the answer at the following 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

You have to use Angular Forms and mark the field as required 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, you have to import:

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

And:

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);
  }
  • Related