Reputation: 1042
I'm trying to establish a simple template driven form validation, with #password="ngModel"
at the input file, when I read password.length
i get undefined
and i dont understand why
My angular form is:
<form #f="ngForm">
<input class="form-control" placeholder='a' type="text" name="password" id="password" [(ngModel)]="renewPasswordData.password"
#password="ngModel">
{{password.length == null}} //<-- returns true
<button [disabled]="password.length == 0" class="btn btn-success btn-block"> //<-- it not works
{{"changePassword.change" | translate}}
</button>
</form>
The ts file:
import { Router } from '@angular/router';
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { RenewPassword } from 'src/app/models/others/RenewPassword';
@Component({
selector: 'app-change-password',
templateUrl: './change-password.component.html',
styleUrls: ['./change-password.component.css']
})
export class ChangePasswordComponent implements OnInit {
renewPasswordData = new RenewPassword("12", "");
constructor(private router: Router) {
console.log(this.renewPasswordData.password.length) //<-- return 2 (correct)
}
ngOnInit() {
}
}
The model:
export class RenewPassword {
constructor(
public password: String,
public rePassword: string
) {
}
}
My ngModule Imports
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
stackblitz: https://stackblitz.com/edit/angular-uzjqdq
Upvotes: 1
Views: 176
Reputation: 73367
We need to remember, you have registered password
as a form control
. So your actual value is inside password.value
, so that is what you need to check.
So check your condition on the button like:
<button [disabled]="password.value?.length === 0">
send
</button>
Upvotes: 1
Reputation: 135
if you need length for validation than please try below code, just set password minlength and maxlength
<input type="text" #password="ngModel" name="password" [(ngModel)]="renewPasswordData.password" minlength="2" maxlength="5"/>
<div *ngIf="password.invalid">
Invalid Password
</div>
Upvotes: 0