farcasmihai91
4/22/2018 - 4:10 PM

Angular - Reactive Form using FormBuilder and AngularMaterial

import { Component, Output } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';
import { EventEmitter } from 'events';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @Output() formSubmitEvent: EventEmitter = new EventEmitter();
  @Output() formCancelEvent: EventEmitter = new EventEmitter();

  public allTags: any[] = [1, 2, 3, 4, 5, 6];
  public bookForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.bookForm = this.fb.group({
      title: ['', Validators.required],
      author: ['', Validators.required],
      tags: [[]]
    });
  }

  submit(formData) {
    return this.formCancelEvent.emit(formData);
  }

  cancel() {
    return this.formCancelEvent.emit(null);
  }
}


// <form [formGroup]="bookForm">
//   <mat-form-field floatLabel="Title">
//     <mat-label>Title</mat-label>
//     <input matInput formControlName="title" placeholder="Title" required>
//   </mat-form-field>

//   <mat-form-field floatLabel="Author">
//     <mat-label>Author</mat-label>
//     <input matInput formControlName="author" placeholder="Author" required>
//   </mat-form-field>

//   <mat-form-field>
//     <mat-select placeholder="Tags" formControlName="tags" multiple>
//       <mat-select-trigger>
//         {{bookForm.controls['tags'].value ? bookForm.controls['tags'].value[0] : ''}}
//         <span *ngIf="bookForm.controls['tags'].value?.length > 1" class="example-additional-selection">
//           (+ {{bookForm.controls['tags'].value.length - 1}} others)
//         </span>
//       </mat-select-trigger>
//       <mat-option *ngFor="let tag of allTags" [value]="tag">{{tag}}</mat-option>
//     </mat-select>
//   </mat-form-field>

//   <div class="form-footer">
//     <button color="primary" type="submit" (click)="submit(bookForm.value)" mat-raised-button>Save</button>
//     <button type="button" mat-raised-button (click)="cancel()">Cancel</button>
//   </div>
// </form>