Template Driven Forms

Goals:

  • Implement a form with different kinds of form elements
  • Display validation errors
  • Submit buttons.

Create the new component called contact-form

ng g c contact-form

<div class="jumbotron">
  <div class="container">
    <h1 class="display-4">contact us!</h1>
  </div>
</div>
<div class="container">
<form>
<div class="form-group">
  <label for="firstName">firstName</label>
  <input id="firstName" type="text" class="form-control">
</div>
<div class="form-group">
  <label for="comment">Comment</label>
  <textarea id="comment" cols="30" rows="10" class="form-control"></textarea>
</div>
<button class="btn btn-primary">submit</button>
</form>
</div>

Each input field has a FormControl class in Angular to control the validation of content input.

  • Value
  • touched
  • untouched
  • dirty
  • pristine
  • errors

FormGroup -> multiple FormControls

  • Value
  • touched
  • untouched
  • dirty
  • pristine
  • errors

Creating Control

  • Directives (Template-Driven)
    • Good for simple forms
    • simple validation
    • easier to create 
    • less code 
  • Code (Reactive Form)
    • More control over validation logic
    • Good for complex forms
    • Unit testable

 

Leave a Reply

Your email address will not be published. Required fields are marked *