pablocattaneo
7/19/2017 - 1:32 PM

Form ready to use!

Form ready to use!

.container {
  margin-top: 30px;
}

input.ng-invalid.ng-touched {
  border: 1px solid red;
}
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('f') signupForm: NgForm; /* get access to the ngForm object using ViewChild decoration and pass as parameter "selector" the local reference using in the template */
  defaultQuestion = 'teacher';
  answer = '';
  genders = ['male', 'female', 'other'];
  user = {
    username: '',
    email: '',
    secretQuestion: '',
    answer: '',
    gender: ''
  };
  submitted = false;

  suggestUserName() {
    const suggestedName = 'Superuser';
    // this.signupForm.setValue({
    //   userData: {
    //     username: suggestedName,
    //     email: ''
    //   },
    //   secret: 'pet',
    //   questionAnswer: '',
    //   gender: 'male'
    // });
    /* this.signupForm.form ( get access to the form object inside ngForm object )*/
    this.signupForm.form.patchValue({
      userData: {
        username: suggestedName
      }
    });
  }

  // onSubmit(form: NgForm) {
  //   console.log(form);
  // }

  onSubmit() {
    console.log(this.signupForm);
    this.submitted = true;
    this.user.username = this.signupForm.value.userData.username;
    this.user.email = this.signupForm.value.userData.email;
    this.user.secretQuestion = this.signupForm.value.secret;
    this.user.answer = this.signupForm.value.questionAnswer;
    this.user.gender = this.signupForm.value.gender;
    
    /* Resets the values and the states, touched, valid etc. It is to say, sets the form as it were the first time the user load the page */
    this.signupForm.reset(); 
  }
}
<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
       <!-- #f="ngForm" localReference to use in @ViewChild -->
      <form (ngSubmit)="onSubmit()" #f="ngForm">
         <!-- 
              ngModelGroup="userData" Group inputs username and email into an object called userData into form object
        -->
        <div
          id="user-data"
          ngModelGroup="userData"
          #userData="ngModelGroup"> 
          <div class="form-group">
            <label for="username">Username</label>
            <!-- ngModel directive indicates to angular that it input is a controller in the form-->
            <input
              type="text"
              id="username"
              class="form-control"
              ngModel
              name="username"
              required>
          </div>
          <button
            class="btn btn-default"
            type="button"
            (click)="suggestUserName()">Suggest an Username</button>
          <div class="form-group">
            <label for="email">Mail</label>
            <input
              type="email"
              id="email"
              class="form-control"
              ngModel
              name="email"
              required
              email
              #email="ngModel">
            <!-- Shows the message if the input is not valid and was 'visited' for de user. Angular access to this properties throught #email="ngModel"-->
            <span class="help-block" *ngIf="!email.valid && email.touched">Please enter a valid email!</span>
          </div>
        </div>
        <p *ngIf="!userData.valid && userData.touched">User Data is invalid!</p>
        <div class="form-group">
          <label for="secret">Secret Questions</label>
          <!-- [ngModel]="defaultQuestion" // One way bindig load the default option value set ted in the property defaultQuestion -->
          <select
            id="secret"
            class="form-control"
            [ngModel]="defaultQuestion"
            name="secret">
            <option value="pet">Your first Pet?</option>
            <option value="teacher">Your first teacher?</option>
          </select>
        </div>
        <div class="form-group">
          <textarea
            name="questionAnswer"
            rows="3"
            class="form-control"
            [(ngModel)]="answer"></textarea>
        </div>
        <p>Your reply: {{ answer }}</p>
        <div class="radio" *ngFor="let gender of genders">
          <label>
            <input
              type="radio"
              name="gender"
              ngModel
              [value]="gender"
              required>
            {{ gender }}
          </label>
        </div>
        <button
          class="btn btn-primary"
          type="submit"
          [disabled]="!f.valid">Submit</button>
      </form>
    </div>
  </div>
  <hr>
  <div class="row" *ngIf="submitted">
    <div class="col-xs-12">
      <h3>Your Data</h3>
      <p>Username: {{ user.username }}</p>
      <p>Mail: {{ user.email }}</p>
      <p>Secret Question: Your first {{ user.secretQuestion }}</p>
      <p>Answer: {{ user.answer }}</p>
      <p>Gender: {{ user.gender }}</p>
    </div>
  </div>
</div>