Fjordo
Fjordo

Reputation: 872

angular 2, validate form if at least one input is typed

I'm quite new to Angular, and I've already searched the web, without finding a correct solution for my situation.

I have a dynamic form created by a *ngFor. I need to disabled the submit button if the inputs are all empty and show the alert div; but I need to enable the submit if at least one of those forms contains something different from ''.

Here is my html code

<form class="form-inline" #form="ngForm">
    <div class="form-group" *ngFor="let meta of state.metaById; let i = index" style="margin: 5px">
      <label>{{meta.nome}}</label>
      <input type="text" class="form-control" #nome (blur)="inputInArray(nome.value, i);">
    </div>
    <button type="button" class="btn btn-primary" (click)="getCustomUnitaDocumentaliRow(this.param)" [disabled]="fieldNotCompiled">invia</button> 
</form>
<div class="alert-notification" [hidden]="!fieldNotCompiled">
    <div class="alert alert-danger">
      <strong>Va compilato almeno un campo.</strong>
    </div>
</div>

and here is my Typescript code

inputInArray(nome: string, indice) {
if (this.state.controlloMetaId = true) {
  this.state.metadatoForm[indice] = nome;
}
// this.fieldNotCompiled = false;
for (const i in this.state.metaById) {
  console.log(this.state.metadatoForm);
  if (isUndefined(this.state.metadatoForm[i]) || this.state.metadatoForm[i] === '') {
    this.fieldNotCompiled = true && this.fieldNotCompiled;
  } else {
    this.fieldNotCompiled = false && this.fieldNotCompiled;
  }
  console.log(this.fieldNotCompiled);
}

With this code I can check the first time a user type something in one input, but it fails if it empty one of them (or all of them)

Thanks for your time

Upvotes: 2

Views: 1839

Answers (1)

Vega
Vega

Reputation: 28701

UPDATE

Check if any input got a change that is different from empty or space, just by doing:

<input ... #nome (input)="fieldNotCompiled = !nome.value.trim()" ....>

DEMO


You can set a listener to the form changes:

@ViewChild('form') myForm: NgForm;
....
ngOnInit() {
    this.myForm.valueChanges.subscribe((value: any) => {
         console.log("One of the inputs has changed");
    });
}

Upvotes: 4

Related Questions