Jesper Jesper - 9 months ago 25
HTML Question

Div should be hidden but is not

I'm trying to make a login form, but I'm having some trouble with error messages.

I want the 2nd div to be hidden if the form is not submitted, or if the form is submitted AND the password is valid.

The html below is not working:

<div class="form-input">
<input #password type="password" name="password"
placeholder="Enter Password" required ngModel>

<div class="alert alert-danger" [hidden]="!form.submitted || (form.submitted && password.valid)">
Please enter your password.
</div>
</div>


The 2nd div is hidden when the page is first loaded, but if I enter a valid password and press the submit button, it is no longer hidden. What am I doing wrong?

Answer Source

You are using html input tag without FormGroup. So it does not have a valid property. Try to check for value instead.

[hidden]="!form.submitted || (form.submitted && password.value)"

NOTE: As suggested by @Jesper !password.errors.required will also work.

Or if you want to check for validity, have a function in the component which checks for validity and call in [hidden] attribute

In component:

isPasswordValid():boolean{
//check this.password validity and return boolean.
}

The [hidden] attribute:

[hidden]="!form.submitted || (form.submitted && isPasswordValid())"