Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 hidden div not working properly

I 'm currently trying to make a simple login form using Bootstrap 4 / Angular 4. Thing is, basing my HTML template on the documentation available on https://angular.io/docs/ts/latest/guide/forms.html, I cannot get the error messages to work if the input is empty. This is what I have so far:

<label>User Name:</label>
<input id="name"
    #name
    placeholder="user name" 
    class="form-control mb-md-3"
    (keyup.enter)="login(name.value, password.value)"
    name="username"
    required>
<div [hidden]="!name.valid || !name.pristine"
    class="alert alert-danger">User name is required</div>

I'm not sure if I need to have two-way binding to a model or anything, I'm not understanding the documentation fully. If it helps, I do have a class for it:

export class User {
  constructor(
    public id: number,
    public name: string,
    public password: string
  ) {}
}

Also, for now this is not going to a service or anything, it's just a small demo screen that will support routing.

like image 341
Manuel Santiago Yépez Avatar asked Oct 17 '22 13:10

Manuel Santiago Yépez


1 Answers

You should use the ngModel directive. This can be bound to some object, or will just make .invalid, .valid, etc.. available to you. Also, you should reference this ngModel, not the input element.

This works:

<label>User Name:</label>
<input id="name"
   #name="ngModel"
   placeholder="user name"
   class="form-control mb-md-3"
   (keyup.enter)="login(name.value, password.value)"
   name="username" required
   ngModel>
<div *ngIf="name.invalid && name.dirty" class="alert alert-danger">User name is required</div>
like image 95
Gauss Avatar answered Nov 15 '22 10:11

Gauss