Form Controls in Angular 6


Create new folder named learnangular5withrealapps and select to this folder in Visual Studio Code

Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6




Create new folder, named entities in src\app folder. In this folder, create new TypeScript file, named account.entity.ts contain account information as below:

export class Account {

    username: string;
    password: string;
    description: string;
    status: boolean;
    gender: string;
    languages: string[];
    role: string;
    certificates: string[];

}

Create new TypeScript file, named app.component.ts in src\app folder.

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

import { Account } from './entities/account.entity';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

  genders: any;
  roles: any;
  languages: any;
  registerForm: FormGroup;
  checkedList: string[];
  certificates: any;

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {

    this.checkedList = [];

    this.certificates = [
      { value: 'cer1', display: 'Certificate 1' },
      { value: 'cer2', display: 'Certificate 2' },
      { value: 'cer3', display: 'Certificate 3' },
      { value: 'cer4', display: 'Certificate 4' },
      { value: 'cer5', display: 'Certificate 5' }
    ];

    this.genders = [
      { value: 'F', display: 'Female' },
      { value: 'M', display: 'Male' }
    ];

    this.roles = [
      { id: 'r1', name: 'Role 1' },
      { id: 'r2', name: 'Role 2' },
      { id: 'r3', name: 'Role 3' },
      { id: 'r4', name: 'Role 4' }
    ];

    this.languages = [
      { id: 'lang1', name: 'Language 1' },
      { id: 'lang2', name: 'Language 2' },
      { id: 'lang3', name: 'Language 3' },
      { id: 'lang4', name: 'Language 4' },
      { id: 'lang5', name: 'Language 5' }
    ];

    this.registerForm = this.formBuilder.group({
      username: '',
      password: '',
      description: '',
      status: true,
      gender: this.genders[0].value,
      languages: [],
      role: [],
      certificates: []
    });

  }

  save(): void {
    let account: Account = this.registerForm.value;
    account.languages = this.checkedList;
    this.displayAccountInfoConsole(account);
  }

  displayAccountInfoConsole(account: Account) {
    console.log('Username: ' + account.username);
    console.log('Password: ' + account.password);
    console.log('Description: ' + account.description);
    console.log('Gender: ' + account.gender);
    console.log('Status: ' + account.status);
    console.log('Languages List');
    for (var i = 0; i < account.languages.length; i++) {
      console.log(account.languages[i]);
    }
    console.log('Role: ' + account.role);
    console.log('Certificates List');
    for (var i = 0; i < account.certificates.length; i++) {
      console.log(account.certificates[i]);
    }
  }

  onCheckboxChange(option, event) {
    if (event.target.checked) {
      this.checkedList.push(option.id);
    } else {
      for (var i = 0; i < this.languages.length; i++) {
        if (this.checkedList[i] == option.id) {
          this.checkedList.splice(i, 1);
        }
      }
    }
  }

}




Create new file, named app.component.html in src\app folder

<h3>Register Form</h3>
<form [formGroup]="registerForm" (ngSubmit)="save()">
    <table>
        <tr>
            <td>Username</td>
            <td>
                <input type="text" formControlName="username">
            </td>
        </tr>
        <tr>
            <td>Password</td>
            <td>
                <input type="password" formControlName="password">
            </td>
        </tr>
        <tr>
            <td valign="top">Description</td>
            <td>
                <textarea cols="20" rows="5" formControlName="description"></textarea>
            </td>
        </tr>
        <tr>
            <td valign="top">Gender</td>
            <td>
                <div *ngFor="let gender of genders">
                    <input type="radio" formControlName="gender"
                        value="{{gender.value}}"> {{gender.display}}
                </div>
            </td>
        </tr>
        <tr>
            <td valign="top">Status</td>
            <td>
                <input type="checkbox" formControlName="status">
            </td>
        </tr>
        <tr>
            <td valign="top">Languages</td>
            <td>
                <div *ngFor="let language of languages">
                    <input type="checkbox"
                        formControlName="languages"
                        value="{{language.id}}"
                        (change)="onCheckboxChange(language,$event)"> {{language.name}}
                </div>
            </td>
        </tr>
        <tr>
            <td valign="top">Role</td>
            <td>
                <select formControlName="role">
                    <option *ngFor="let role of roles" value="{{role.id}}">
                        {{role.name}}
                    </option>
                </select>
            </td>
        </tr>
        <tr>
                <td valign="top">Certificates</td>
                <td>
                    <select formControlName="certificates" multiple="multiple">
                        <option *ngFor="let certificate of certificates"
                            value="{{certificate.value}}">
                            {{certificate.display}}
                        </option>
                    </select>
                </td>
            </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <input type="submit" value="Save">
            </td>
        </tr>
    </table>
</form>

In app.module.ts file in src\app folder. Add new component to module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

In Terminal windows in Visual Studio Code and type: ng serve --open, program will open url http://localhost:4200/ on browser




I recommend you refer to the books below to learn more about the knowledge in this article: