legiahoang
8/15/2017 - 8:51 AM

form validate

form validate

import { Comment } from './../shared/comment';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Component, OnInit, Input } from "@angular/core";
import { Dish } from "./../shared/dish";
import { DishService } from "./../services/dish.service";
import { Params, ActivatedRoute } from "@angular/router";
import { Location } from "@angular/common";
import "rxjs/add/operator/switchMap";

@Component({
  selector: "app-dishdetail",
  templateUrl: "./dishdetail.component.html",
  styleUrls: ["./dishdetail.component.scss"]
})
export class DishdetailComponent implements OnInit {
  dish: Dish;
  dishIds: number[];
  prev: number;
  next: number;
  addcommentForm: FormGroup;
  comment: Comment;

  formErrors = {
    author: '',
    rating: '',
    comment: ''    
  };

  validationMessages = {
    author: {
      required: "Author Name is required",
      minlength: "Author Name must be at least 2 characters long.",
      maxlength: "Author Name cannot be more than 25 characters long."
    },
    rating: {

    },
    comment: {
      required: "Comment is required."      
    }
  }


  constructor(
    private dishService: DishService,
    private route: ActivatedRoute,
    private location: Location,
    private formBuilder: FormBuilder
  ) {
    this.createForm();

  }

  ngOnInit() {
    this.dishService.getDishIds().subscribe(dishIds => {
      this.dishIds = dishIds;
    });
    this.route.params
      .switchMap((params: Params) => this.dishService.getDish(+params["id"]))
      .subscribe(dish => {
        this.dish = dish;
        this.setPrevNext(dish.id);
      });
  }

  setPrevNext(dishId: number): void {
    let index = this.dishIds.indexOf(dishId);
    this.prev = this.dishIds[
      (this.dishIds.length + index - 1) % this.dishIds.length
    ];
    this.next = this.dishIds[
      (this.dishIds.length + index + 1) % this.dishIds.length
    ];
  }

  goBack(): void {
    this.location.back();
  }

  createForm(){
    this.addcommentForm = this.formBuilder.group({
      author: ["",[Validators.required,Validators.minLength(2),Validators.maxLength(25)]],      
      rating: [],
      comment: ["",Validators.required]
    })
    this.addcommentForm.valueChanges.subscribe(data => {
      this.onValueChanged(data);
    })
    this.onValueChanged();
  }

  onValueChanged(data?: any) {
    if(!this.addcommentForm){
      return;
    }
    const form = this.addcommentForm;
    for(const field in this.formErrors){
      this.formErrors[field] = "";// clear the previous message (if any)
      const control = form.get(field);            
      if(control && control.dirty && !control.valid){       
       const messages = this.validationMessages[field];       
       for (const key in control.errors){
          this.formErrors[field] += messages[key] + " ";
       }
      }
    }
  }

  onSubmit() {
    this.comment =this.addcommentForm.value;
    console.log(this.comment);
    this.addcommentForm.reset({
      author: "",
      rating: "",
      comment: ""
    })
  }

  log(val){
    console.log(val);
  }
}
<div class="container" fxLayout="row" fxLayout.sm="column" fxLayout.xs="column" fxLayoutAlign.gt-md="space-around-center"
  fxLayoutGap="10px" fxLayoutGap.xs="0">
  <div fxFlex="40" *ngIf="dish">
    <md-card>
      <md-card-header>
        <md-card-title>
          <h3>{{dish.name | uppercase}}</h3>
        </md-card-title>
      </md-card-header>
      <img md-card-image src="{{dish.image}}" alt="{{dish.name}}">
      <md-card-content>
        <p>{{dish.description}}</p>
      </md-card-content>
      <md-card-actions>
        <button md-button bind-routerLink="['/dishdetail',prev]">
            <span class="fa fa-chevron-left fa-lg"></span>
        </button>
        <button md-button (click)="goBack()">BACK</button>
        <button md-button>LIKE</button>
        <button md-button>SHARE</button>
        <span class="flex-spacer"></span>
        <button md-button bind-routerLink="['/dishdetail',next]">
           <span class="fa fa-chevron-right fa-lg"></span>
        </button>
      </md-card-actions>
    </md-card>
  </div>
  <div fxFlex="40" *ngIf="dish">

    <md-list>
      <h3 md-subheader>Comments </h3>
      <md-divider></md-divider>
      <md-list-item *ngFor="let comment of dish?.comments">
        <p md-line>{{comment.comment}}</p>
        <p md-line>{{comment.rating}} Stars</p>
        <p md-line>-- {{comment.author}} {{comment.date | date}}</p>
      </md-list-item>
    </md-list>
      
    <form novalidate bind-formGroup="addcommentForm" (ngSubmit)="onSubmit()">
      <md-list>
        <p>
        <md-input-container class="full-width">
          <input mdInput formControlName="author" placeholder="Name" type="text" required>
          <md-hint>
            <span bind-hidden="!(formErrors.author)">{{formErrors.author}}</span>
          </md-hint>
        </md-input-container>
        </p>
        <md-slider formControlName="rating" tickInterval="1" thumbLabel min="1" max="5" step="1" value="4"></md-slider>
        <p class="full-witdth">
          <md-input-container class="full-width">
            <textarea mdInput formControlName="comment" placeholder="Your Comment" rows="6" required></textarea>
            <md-hint>
                <span bind-hidden="!formErrors.comment">{{formErrors.comment}}</span>
            </md-hint>
          </md-input-container>          
        </p>
        <button md-button type="submit" class="background-primary text-floral-white" bind-disabled="addcommentForm.invalid">Submit</button>
      </md-list>
    </form>

  </div>
  

  <div bind-hidden="dish">    
    <md-spinner></md-spinner>
    <h4>Loading...Please Wait</h4>
  </div>
</div>