2017-10-17 58 views
0

我在做一个表单。如果密码字段小于6个字符,它应该显示一个错误信息,如果它>> = 6个字符,它不应该显示。Angular 4:错误消息应该消失在6个字符以上

我得到了具有适当条件的错误消息,但是当我在字段中键入6个字符时,消息不会消失。

我想这个错误消息动态地出现和消失,就像它为'所需'的条件。

我该怎么做?

这里是模板:

<div class="form-group"> 
    <label for="password">Password</label> 
    <input 
    type="text" 
    name="password" 
    id="password" 
    class="form-control" 
    formControlName="password"> 
    <div *ngIf="signUpForm.get('password').touched"> 
    <p class="help-block" 
     *ngIf="!signUpForm.get('password').valid">This field is required</p> 
    <p class="help-block" 
     *ngIf="!signUpForm.get('password').hasError('minlength')">Password must be at list 6 characters</p> 
    </div> 
</div> 

这里是TS文件:

signUpForm: FormGroup; 

ngOnInit(){ 
    this.signUpForm = new FormGroup({ 
    'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(6)]), 
    'password':new FormControl(null, Validators.required) 
    }); 
} 
+0

试试这个password.hasError('minlength')&&!password.hasError('required')和'password':['',[Validators.required,Validators.minLength(8)]], –

+0

remove! ngIf =“signUpForm.get('password')。hasError('minlength')” – Vega

回答

1

这条线:

<p class="help-block" *ngIf="!signUpForm.get('password').hasError('minlength')">Password must be at list 6 characters</p> 

意味着您显示错误时,密码没有一个错误。删除感叹号,更改为:

<p class="help-block" *ngIf="signUpForm.get('password').hasError('minlength')">Password must be at list 6 characters</p> 
1

密码首先在表单初始化添加验证

this.signUpForm = new FormGroup({ 
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(6)]), 
      'password':new FormControl(null, [Validators.required, Validators.minLength(6)]) 
     }); 

现在做出一些改变你的HTML代码

<p class="help-block" *ngIf="signUpForm.get('password').hasError('minlength') && !signUpForm.get('password').hasError('required')">Password must be at list 6 characters</p> 
0

OK,想通它出来了,谢谢大家的回答

<input 
     type="text" 
     name="password" 
     id="password" 
     class="form-control" 
     formControlName="password" 
     > 
      <div class="help-block" 
      *ngIf="signUpForm.get('password').touched"> 
       <p 
        *ngIf="signUpForm.get('password').hasError('required'); else characterNumber">This field is required</p> 
         <ng-template #characterNumber> 
         <p  
         *ngIf="signUpForm.get('password').hasError('minlength')">Password must be at list 6 characters</p> 
         </ng-template>  
      </div> 
+0

welcome @ florent-arlandis –