Skip to content
  • Home
  • Search
  • Tools
  • About
  • Terms of Service Agreement
  • Log In
  • Guest

Angular From Scratch Tutorial – Step 7: Forms

Posted on March 13, 2021October 15, 2022 By Andre Dias
angular, javascript

Angular From Scratch Tutorial – Index

PREVIOUS: Angular From Scratch Tutorial – Step 6: Service And Dependency Injection

 

Table of Contents

  • TARGET
    • Summary
  • Choosing an approach
    • Key differences
    • Common form foundation classes
    • Template-driven models
    •  Reactive forms
  • Setup
    • >PROBLEM
    • >SOLUTION
    • >ENV
  • Accessing field values with ngForm
  • Referencing Snippets
  • ngSubmit
    • Snippets
  • <select>

TARGET

Revision for working with forms when you have already worked with Angular but after some time you need to refresh your memory.

The theory comes from Introduction to forms in Angular doc.
This page is a summary for fast revision.
If it is your first time, you’d better go to Angular Documentation.

Summary

One of the advantages of working directly with form control objects is that value and validity updates are always synchronous and under your control.
Angular offers two form-building technologies: reactive forms and template-driven forms.
These two belong to the @angular/forms library and share a series of form control classes.
They even have their own modules: ReactiveFormsModule and FormsModule.
Reactive forms provide synchronous access to the data model, immutability with observable operators, and change tracking through observable streams.
Template-driven forms let direct access modify data in your template, but are less explicit than reactive forms because they rely on directives embedded in the template, along with mutable data to track changes asynchronously.

@SEE: more at:
Learn Angular with free step by step angular tutorials [ML44649]

 

Choosing an approach

Reactive forms and template-driven forms process and manage form data differently. Each approach offers different advantages.

FORMS DETAILS
Reactive forms Provide direct, explicit access to the underlying forms object model. Compared to template-driven forms, they are more robust: they’re more scalable, reusable, and testable. If forms are a key part of your application, or you’re already using reactive patterns for building your application, use reactive forms.
Template-driven forms Rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They’re straightforward to add to an app, but they don’t scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.

 

Key differences

Common form foundation classes

Template-driven models

 

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-forms2',
  template: `
    Favorite Color: <input type="text" [(ngModel)]="favoriteColor">
  `,
  styleUrls: ['./forms2.component.sass']
})
export class Forms2Component implements OnInit {

  favoriteColor = '';

  constructor() { }

  ngOnInit(): void {
  }

}

 Reactive forms

 

import { Component, OnInit } from '@angular/core'; 
import { FormControl } from '@angular/forms'; 
@Component({ 
	selector: 'app-forms1', 
	template: ` Favorite Color: <input type="text" [formControl]="favoriteColorControl"> `, 
	styleUrls: ['./forms1.component.sass'] }) 
export class Forms1Component implements OnInit { 
	favoriteColorControl = new FormControl(''); 
	constructor() { } 
	ngOnInit(): void { } 
}

Additional Links

stackblitz reactive form

stackblitz template-driven

 

Setup

>PROBLEM

Running angular using ngModels, you get:

error NG8002: Can’t bind to ‘formControl’ since it isn’t a known property of ‘input’.

Example, implementing the following code:

You get:

 

>SOLUTION

There are at least two things to be observed.

1. Require modules setup.

Set the required modules in app.modules.ts:

import { FormsModule, ReactiveFormsModule } from “@angular/forms”;

…

@NgModule({

declarations: [

//…

],

imports: [

//…

FormsModule,

ReactiveFormsModule,

],

*** IMPORTANT NOTE:

If you are using a page under its specific module, declare in that module two.

Example:

app

+–forms-lab

+– forms1

— forms-lab.module.ts

Edit forms-lab.module.ts and declare both modules referred to above.

2. Make sure that you have not overwritten the angular modules: 

It is something easy to happen, for instance, if you create a module called forms, as it is:


ng g m forms

This command will generate a FormsModule that overrides the angular’s module.
This conflict causes the same issue.

If it happened, delete, and recreate it with another name.

@SEE:

https://stackoverflow.com/questions/43220348/cant-bind-to-formcontrol-since-it-isnt-a-known-property-of-input-angular

>ENV

Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64

Accessing field values with ngForm

 

  <h6><a href="https://angular.io/api/forms/NgForm">https://angular.io/api/forms/NgForm</a></h6>
  <form #itemForm="ngForm" (ngSubmit)="onSubmit(itemForm)">
    <label for="name">Name</label>&nbsp;
    <input type="text" id="name" class="form-control" name="name" ngModel required />&nbsp;&nbsp;
    <button type="submit">Submit</button>
  </form>
  
  import {NgForm, FormGroup} from '@angular/forms';
  
  onSubmit(f: NgForm): void {
    console.log(f.value);  // { first: '', last: '' }
    console.log(f.valid);  // false
    alert(f.value.emailid);
  }

Referencing Snippets

>snippet #1
- .ts file:
    // convenience getter for easy access to form fields
    get f() { return this.loginForm.controls; }

- .html file:
<div *ngIf="submitted && f.username.errors" class="invalid-feedback">
	<div *ngIf="f.username.errors.required">Username is required</div>
</div>


>snippet #2
- .html file:
    <form
      *ngIf="!isLoggedIn"
      name="form"
      (ngSubmit)="f.form.valid && onSubmit()"
      #f="ngForm"
      novalidate
    >

 

From Angular doc: NgForm

 

import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
      <input name="first" ngModel required #first="ngModel">
      <input name="last" ngModel>
      <button>Submit</button>
    </form>

    <p>First name value: {{ first.value }}</p>
    <p>First name valid: {{ first.valid }}</p>
    <p>Form value: {{ f.value | json }}</p>
    <p>Form valid: {{ f.valid }}</p>
  `,
})
export class SimpleFormComp {
  onSubmit(f: NgForm) {
    console.log(f.value);  // { first: '', last: '' }
    console.log(f.valid);  // false
  }
}

 

ngSubmit

SEE:
– Build angular 13 forms with example [ML44183]
– Angular: FormGroupDirective

Snippets

- .html file:

<form
      *ngIf="!isLoggedIn"
      name="form"
      (ngSubmit)="f.form.valid && onSubmit()"
      #f="ngForm"
      novalidate
    >

- .ts file:
  onSubmit(): void {
    const { username, password } = this.form;

    this.authService.login(username, password).subscribe({
      next: data => {
        this.tokenStorage.saveToken(data.accessToken);
        this.tokenStorage.saveUser(data);

        this.isLoginFailed = false;
        this.isLoggedIn = true;
        this.roles = this.tokenStorage.getUser().roles;
        this.reloadPage();
      },
      error: err => {
        this.errorMessage = err.error.message;
        this.isLoginFailed = true;
      }
    });
  }

 

<select>

>component.ts

activities: any;
activity: string;

  constructor(
    private activityService: ActivityService,
    private todosService: TodosService,
  ) {
    activityService.load(this.email, this.stoken).subscribe((objs) => {
      this.activities = [];
      for (let i = 0; i < objs.activities.length; i++) {
        this.activities[i] = objs.activities[i];
      }
    });
    this.activity = 'all activities';
  }


  newTodoSubmit(): void {
    alert(this.activity);
  }


>component.html

<select id="activities_id" class="form-select caret" [(ngModel)]="activity"
  style="border-color: transparent !important; border-width: 0px !important; margin-top: 0px; font-size: 12px !important; width: 120px !important;">
  <option value="{{activity}}" selected>all activities</option>
  <option value="{{activity.name}}" *ngFor="let activity of activities">{{activity.name}}</option>
</select>

 

 

Angular From Scratch Tutorial – Index

PREVIOUS: Angular From Scratch Tutorial – Step 6: Service And Dependency Injection

 

Andre Dias
Andre Dias

Brazilian system analyst graduated by UNESA (University Estácio de Sá – Rio de Janeiro). Geek by heart.

Post navigation

❮ Previous Post: Angular From Scratch Tutorial – Step 6: Service And Dependency Injection
Next Post: COVID-19: MASKS – SUMMARY ❯

Search

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
angular
bootstrap
browser
computer science
container
data persistence
database
devops
editors
hardware
health
hosting
info
internet
it
java
javascript
network
node.js
play
protocol
security
self-help
selfhelp
server
services
soft
software engeneering
sql
support
Systems
techs
Uncategorized
versioning
web
web design
windows
wordpress

Recent Posts

  • Angular From Scratch Tutorial – Step 9: Modal
  • Angular From Scratch Tutorial – Step 8: Miscellany
  • Angular From Scratch Tutorial – Index
  • angular: Reading JSON files
  • NODE.JS: SEQUELIZE: MVC Project – 4TH STEP

Categories

  • angular (19)
  • bootstrap (6)
  • browser (4)
  • computer science (4)
  • container (1)
  • data persistence (2)
  • database (11)
  • devops (1)
  • editors (1)
  • hardware (4)
  • health (2)
  • hosting (1)
  • info (1)
  • internet (2)
  • it (1)
  • java (13)
  • javascript (32)
  • network (6)
  • node.js (1)
  • play (1)
  • protocol (1)
  • security (4)
  • self-help (1)
  • selfhelp (1)
  • server (2)
  • services (1)
  • soft (1)
  • software engeneering (1)
  • sql (1)
  • support (2)
  • Systems (1)
  • techs (3)
  • Uncategorized (2)
  • versioning (6)
  • web (1)
  • web design (5)
  • windows (3)
  • wordpress (4)

Copyright © 2025 .

Theme: Oceanly by ScriptsTown

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT