表单提交后使用错误消息作为标签

时间:2018-12-04 08:13:56

标签: angular typescript angular6

我有此表格,希望用于重置用户密码:

HTML代码:

<form class="grid-wrapper" #f="ngForm" *ngIf="stepOne">

  <div class="form-group first-row">
    <label for="name">Username</label>
    <input id="name" type="text" name="name" class="form-control" required [(ngModel)]="user.name">
  </div>

  <div class="form-group second-row">
    <label for="email">Email</label>
    <input id="email" type="text"
           name="email"
           class="form-control"
           email required
           [(ngModel)]="user.email"
           [ngClass]="{ 'is-invalid': nameEmailMismatch || notFound }">
    <div class="invalid-feedback-custom">
      <div *ngIf="nameEmailMismatch">Provided email doesn't belong to current user</div>
      <div *ngIf="notFound">User not found</div>
    </div>
  </div>

  <div class="btn-row third-row">
    <button class="btn btn-primary" [disabled]="f.invalid || loading" (click)="submit()">Reset</button>
  </div>

</form>

<div *ngIf="stepTwo">

  <div>
    <h2>Password reset link has been sent to your email</h2>
  </div>

</div>

<div class="complete" *ngIf="stepFour">
  <p>
    Your password has been reset
  </p>
  <a class="btn btn-primary" routerLink="/login">Login</a>
</div>

组件:

@Component({
  ........
})
export class ResetPasswordNewComponent implements OnInit {

  user: UserReset = new UserReset(null, null, null, null, null, null);

  stepOne = true;
  stepTwo = false;

  loading = false;

  nameEmailMismatch = false;
  notFound = false;

  constructor(private resetService: PasswordResetService,
              private route: ActivatedRoute) {
  }

  ngOnInit() {
  }

  submit() {
    this.loading = true;
    this.nameEmailMismatch = false;
    this.notFound = false;

    this.resetService.requestReset(this.user).subscribe(user => {
        this.stepOne = false;
        this.stepTwo = true;
        this.loading = false;
      },
      error => this.handleError(error));
  }

  handleError(error) {
    console.log(error);
    this.loading = false;
    switch (error.error) {
      case 'NAME_AND_EMAIL_MISMATCH':
        this.nameEmailMismatch = true;
        break;
    }

    switch (error.status) {
      case 404:
        this.notFound = true;
        break;
    }

  }
}

提交表单并且找不到用户或密码时,如何显示消息?当前的解决方案是使用具有true和false的变量。例如,在表单提交后使用的标签,还有其他解决方案吗?

2 个答案:

答案 0 :(得分:0)

您可以使用reactiveform,此表单验证提供setError('custom-erro',true/false),并且可以在表单提交调用上进行设置。让我知道您是否需要更清晰的视野。

答案 1 :(得分:0)

您设置了submitted的{​​{1}}属性,如果已提交表单,则该属性为true。

ngForm