Angular7: это правильный способ использовать Validators и FormBuilders - PullRequest
0 голосов
/ 12 мая 2019

Я изучаю, как использовать реактивные формы в Angular 7. В следующем примере используется только 1 вход, в то время как мое приложение использует несколько входных параметров для создания нового объекта Post. Мне было интересно, является ли то, что я делаю, правильным способом, так как я использую несколько полей mat-form-field, и это немного странно, когда я комбинирую это с 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>
...