当我读取password.length时,我试图建立一个简单的模板驱动的表单验证,在输入文件中使用#password =“ ngModel”,我不确定并且不明白为什么
我的角形是:
<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>
ts文件:
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() {
}
}
模型:
export class RenewPassword {
constructor(
public password: String,
public rePassword: string
) {
}
}
我的ngModule导入
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
stackblitz:https://stackblitz.com/edit/angular-uzjqdq
答案 0 :(得分:1)
我们需要记住,您已经将password
注册为form control
。因此,您的实际值在password.value
内部,因此您需要检查一下。
因此,请在按钮上检查您的状况,例如:
<button [disabled]="password.value?.length === 0">
send
</button>
答案 1 :(得分:0)
如果需要验证长度,请尝试以下代码,只需设置密码minlength和maxlength
<input type="text" #password="ngModel" name="password" [(ngModel)]="renewPasswordData.password" minlength="2" maxlength="5"/>
<div *ngIf="password.invalid">
Invalid Password
</div>