似乎无法正确重置我的表单

时间:2019-05-22 08:18:38

标签: angular angular-reactive-forms

因此,我一直在看这里的其他文章,这些文章谈论将您的反应形式重置为angular,但对我而言不起作用。当然,表单的值会重置,但是表单本身会标记为红色,但不会显示错误消息。我希望这一点也消失。

显示表单的组件的打字稿

@Component({
  selector: 'app-comment',
  templateUrl: './comment.component.html',
  styleUrls: ['./comment.component.css']
})
export class CommentComponent implements OnInit {
  @Input('comments') comments: Comment[];
  @Input('imageId') imageId: number;
  public messageForm: FormGroup;
  private _user: string;
  public loggedInUser: User;

  constructor(
    private _commentDataService: CommentDataService,
    private fb: FormBuilder,
    private _authService: AuthenticationService,
    public dialog: MatDialog,
    private _snackBar: MatSnackBar
  ) {
    this.messageForm = this.fb.group({
      message: [
        '',
        [Validators.required, Validators.minLength(3), Validators.maxLength(75)]
      ]
    });
  }

  getErrorMessage(error: any) {
    if (error.required) {
      return 'is required';
    } else if (error.minlength) {
      return `need at least ${error.minlength.requiredLength} characters`;
    } else if (error.maxlength) {
      return `max length is ${error.maxlength.requiredLength}`;
    }
  }

  ngOnInit() {
    this._authService.user$.subscribe(usr => (this._user = usr));
    this._authService.loggedInUser$.subscribe(user => {
      this.loggedInUser = user;
    });
  }

  onSubmit() {
    if (this._user) {
      this._commentDataService
        .postComment(
          this.imageId,
          new Comment(
            this.loggedInUser.firstName + ' ' + this.loggedInUser.lastName,
            this.messageForm.value.message,
            new Date(),
            this.imageId,
            this.loggedInUser.id
          )
        )
        .subscribe(com => {
          console.log(com);
          this.comments.push(com);
          this.messageForm.reset({ message: '' });
        });
    } else {
      this.openSnackBar('You need to be logged in to send a message.');
    }
  }

  private openSnackBar(message: string) {
    this._snackBar.open(message, 'Close', { duration: 2000 });
  }

  isAuthor(comment: Comment): boolean {
    if (this.loggedInUser) {
      return comment.visitorId === this.loggedInUser.id;
    }
    return false;
  }

  openChangeDialog(comment: Comment) {
    const dialogRef = this.dialog.open(ChangeCommentComponent, {
      width: '300px',
      data: {
        comment,
        array: this.comments,
        index: this.comments.indexOf(comment)
      }
    });
  }

  openDeleteDialog(comment: Comment) {
    const dialogRef = this.dialog.open(DeleteCommentComponent, {
      width: '300px',
      height: '200px',
      data: { comment, array: this.comments }
    });
  }
}

表示形式的HTML

<div class="overflow">
  <div
    fxLayout="row"
    fxLayoutAlign="space-between"
    *ngFor="let comment of comments"
  >
    <div>
      <div class="commentDiv" data-cy="comments">
        <span class="user left">{{ comment.author }}: </span>
        <span>{{ comment.content }}</span>
      </div>
      <div class="iconDiv right" *ngIf="isAuthor(comment)">
        <mat-icon class="edit" (click)="openChangeDialog(comment)"
          >edit</mat-icon
        ><mat-icon class="delete" (click)="openDeleteDialog(comment)"
          >delete</mat-icon
        >
      </div>
    </div>
  </div>
</div>
<form [formGroup]="messageForm" (ngSubmit)="onSubmit()" data-cy="commentForm">
  <mat-form-field>
    <input
      matInput
      aria-label="Message"
      placeholder="Message"
      type="text"
      class="browser-default"
      formControlName="message"
    />
    <mat-error
      *ngIf="
        messageForm.get('message')['errors'] &&
        messageForm.get('message').touched
      "
    >
      {{ getErrorMessage(messageForm.get('message')['errors']) }}
    </mat-error>
  </mat-form-field>

  <button mat-raised-button type="submit" [disabled]="!messageForm.valid">
    <mat-icon>send</mat-icon>
  </button>
</form>

更清晰:用户可以在图片上添加评论。当他这样做时,他调用了POST方法(在OnSubmit()内部),我希望清除表单。当我调用this.messageForm.reset()时,它确实清除了表单,但也将其置于无效状态(因为它以红色概述,但是下面没有显示错误消息)。虽然用户b产生的错误不尊重我已经进行的验证,但该表单也将显示为红色,但错误消息将显示在<small>标签中,该标签由Material生成({ {1}})。我正在寻找一种在不引发错误的情况下重置表单的方法。

1 个答案:

答案 0 :(得分:0)

因此,执行此操作的一个好方法是更有效地使用reset()方法。 我建议您创建一个属性isSubmitted并将其设置为true,仅在您的Submit方法内部。 (旁注:由于它只是一个输入,所以我看不出您为什么调用messageForm.value.message。)

然后,在调用reset方法的地方,将其包装在if语句中以检查isSubmitted === true是否可以根据需要添加更多条件。...请参见随附的代码段:

onSubmit() {
 this.isSubmitted = true;
  if (this._user) {
    this._commentDataService
    .postComment(
      this.imageId,
       new Comment(
        this.loggedInUser.firstName + ' ' + this.loggedInUser.lastName,
        this.messageForm.value,
        new Date(),
        this.imageId,
        this.loggedInUser.id
      )
    )
    .subscribe(com => {
      console.log(com);
      this.comments.push(com);

     if (this.isSubmitted.true) {`
        this.messageForm.reset ({
          message: { value: null, disabled: true } 
     });
   }
 }`