나는 일에 로그인 폼 및 경우에는 사용자가 잘못된 자격 증명을 우리가 원하는 표시가 모두 이메일과 비밀번호 필드를 잘못된 메시지를 표시 말하는 로그인하지 못했습니다. 나는 어떻게 설정에 대해 이 필드의 잘못된 관찰 콜백?
템플릿:
<form #loginForm="ngForm" (ngSubmit)="login(loginForm)" id="loginForm">
<div class="login-content" fxLayout="column" fxLayoutAlign="start stretch">
<md-input-container>
<input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email">
</md-input-container>
<md-input-container>
<input mdInput placeholder="Password" type="password" name="password" required [(ngModel)]="password">
</md-input-container>
<p class='error' *ngIf='loginFailed'>The email address or password is invalid.</p>
<div class="extra-options" fxLayout="row" fxLayoutAlign="space-between center">
<md-checkbox class="remember-me">Remember Me</md-checkbox>
<a class="forgot-password" routerLink='/forgot-password'>Forgot Password?</a>
</div>
<button class="login-button" md-raised-button [disabled]="!loginForm.valid">SIGN IN</button>
<p class="note">Don't have an account?<br/> <a [routerLink]="['/register']">Click here to create one</a></p>
</div>
</form>
로그인 방법:
@ViewChild('loginForm') loginForm: HTMLFormElement;
private login(formData: any): void {
this.authService.login(formData).subscribe(res => {
alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
}, error => {
this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
this.loginForm.controls.email.invalid = true;
this.loginForm.controls.password.invalid = true;
});
}
이외에 설정을 입력 잘못된 플래그를 사실 나는've tried 설정하는이메일입니다.유효한
플래그를 false 로 설정loginForm.잘못된
true as well. 아무도 이러한 원인 입력을 표시하는 자신의 잘못된 상태입니다.
에서 구성 요소:
formData.form.controls['email'].setErrors({'incorrect': true});
과 HTML:
<input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email" #email="ngModel">
<div *ngIf="!email.valid">{{email.errors| json}}</div>
추가 줄리아 Passynkova's 응답
을 설정하는 유효성 검사 오류 구성 요소:
formData.form.controls['email'].setErrors({'incorrect': true});
를 해제 유효성 검사 오류 구성 요소:
formData.form.controls['email'].setErrors(null);
조심해야 해제를 사용하여 오류null
으로 이어 오류가 있습니다. 을 유지하려면 몇 가지 주위에 체크를 할 수 있습의 존재에 대한 다른 오류가 먼저:
if (isIncorrectOnlyError){
formData.form.controls['email'].setErrors(null);
}
새로운 버전에서 물자의 2 이는 그 이름을 제어 시작으로 매트 접두사 setErrors()지 않't,작동 대신 Juila's 응답 변경 될 수 있습니다:
formData.form.controls['email'].markAsTouched();
내가 부르는 것을 시도하고 있었다setErrors()
내 ngModelChange 처리기 템플릿에서 형태입니다. 그것은 작동하지 않을 때까지 기다렸다가 하나 진드기와setTimeout()
:
템플릿:
<input type="password" [(ngModel)]="user.password" class="form-control"
id="password" name="password" required (ngModelChange)="checkPasswords()">
<input type="password" [(ngModel)]="pwConfirm" class="form-control"
id="pwConfirm" name="pwConfirm" required (ngModelChange)="checkPasswords()"
#pwConfirmModel="ngModel">
<div [hidden]="pwConfirmModel.valid || pwConfirmModel.pristine" class="alert-danger">
Passwords do not match
</div>
구성 요소:
@ViewChild('pwConfirmModel') pwConfirmModel: NgModel;
checkPasswords() {
if (this.pwConfirm.length >= this.user.password.length &&
this.pwConfirm !== this.user.password) {
console.log('passwords do not match');
// setErrors() must be called after change detection runs
setTimeout(() => this.pwConfirmModel.control.setErrors({'nomatch': true}) );
} else {
// to clear the error, we don't have to wait
this.pwConfirmModel.control.setErrors(null);
}
}
개는 다음과 같이 나아보세요 민감하는 형태입니다.
여기에는 예 작동:
MatchPassword(AC: FormControl) {
let dataForm = AC.parent;
if(!dataForm) return null;
var newPasswordRepeat = dataForm.get('newPasswordRepeat');
let password = dataForm.get('newPassword').value;
let confirmPassword = newPasswordRepeat.value;
if(password != confirmPassword) {
/* for newPasswordRepeat from current field "newPassword" */
dataForm.controls["newPasswordRepeat"].setErrors( {MatchPassword: true} );
if( newPasswordRepeat == AC ) {
/* for current field "newPasswordRepeat" */
return {newPasswordRepeat: {MatchPassword: true} };
}
} else {
dataForm.controls["newPasswordRepeat"].setErrors( null );
}
return null;
}
createForm() {
this.dataForm = this.fb.group({
password: [ "", Validators.required ],
newPassword: [ "", [ Validators.required, Validators.minLength(6), this.MatchPassword] ],
newPasswordRepeat: [ "", [Validators.required, this.MatchPassword] ]
});
}
에 민감하는 형태로,필요한 표시하려면 필드에 잘못된 경우 또 다른 필드를 확인합니다. 에 ng 버전 7 나는 다음과 같다:
const checkboxField = this.form.get('<name of field>');
const dropDownField = this.form.get('<name of field>');
this.checkboxField$ = checkboxField.valueChanges
.subscribe((checked: boolean) => {
if(checked) {
dropDownField.setValidators(Validators.required);
dropDownField.setErrors({ required: true });
dropDownField.markAsDirty();
} else {
dropDownField.clearValidators();
dropDownField.markAsPristine();
}
});
그래서 위의 때 박스에 체크를 설정 드롭다운로 필요하시면 됩니다.더럽습니다. 지 않는 경우't 마크 등과 같은이 다음 그것지't 잘못된 것(에 오류가)려고 할 때까지 양식을 제출하는 상호작용할 수 있습니다.
는 경우에는 확인란을 false 로 설정(체크)우리는 명확한 필요한 검사기에서 드롭다운 리셋하여 깨끗한 상태입니다.
또한 기억에서 탈퇴하 모니터링 분야의 변화!