Angular7:这是使用Validators和FormBuilders的正确方法

时间:2019-05-12 19:27:08

标签: forms validation angular7

我正在学习如何在Angular 7中使用反应形式。下面的示例仅使用1个输入,而我的应用程序使用多个输入参数来创建新的Post对象。我想知道我在做什么是正确的方法,因为我正在使用多个mat-form-fields,将它与formbuilder结合使用时感觉有点奇怪。

TS

export class AddPostComponent implements OnInit {
  @Output() public newPost = new EventEmitter<Post>();
  public post:FormGroup;
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.post = this.fb.group({
      title: this.fb.control('', [Validators.required, Validators.minLength(3)]),
      body: this.fb.control('', [Validators.required, Validators.minLength(3)]),
      pieces: this.fb.control('', [Validators.min(0)]),
    })
  }

  getErrorMessage(errors: any) {
    if (errors.required) {
      return 'is required';
    } else if (errors.minlength) {
      return `needs at least ${errors.minlength.requiredLength} 
        characters (got ${errors.minlength.actualLength})`;
    }
  }
    onSubmit() {
      this.newPost.emit(new Post("Test", this.post.value.title, this.post.value.body, new Date(Date.now()), this.post.value.pieces, 0, [] ));
    }

HTML

<mat-card>
    <form [formGroup]="post" (ngSubmit)='onSubmit()'>
  <mat-form-field>
    <input matInput aria-label="Title" placeholder="Title" type="text" formControlName="title" required />
    <mat-error
          *ngIf="post.get('title')['errors'] && 
            post.get('title').touched">
          {{ getErrorMessage(post.get('title')['errors']) }}
        </mat-error>
  </mat-form-field><br>
  <mat-form-field>
    <textarea matInput aria-label="Body" placeholder="Body" type="text" formControlName="body" required ></textarea>
  </mat-form-field><br>
  <mat-form-field>
      <input matInput aria-label="Pieces" placeholder="Pieces" type="number" formControlName="Pieces" />
    </mat-form-field><br>
  <label class="image-upload-container btn button-wbm">
      <div style="color: #a2a2a2">Image</div>
      <input #imageInput
             type="file"
             title="Upload Image"
             accept="image/*">
    </label>
    <br><br>
    <button type='submit' mat-raised-button [disabled]='!post.valid'>Add Post</button>
    </form>
</mat-card>

0 个答案:

没有答案