Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Custom form control in angular 12

Create custom form control in angular 12 / 13

Aman Jain, December 19, 2021March 19, 2022

In this article i will show you to use FormControl in child component. By default child component can not access the FormGroup and we can not use FormControl or FormControlName in parent child component approach.

You can also read How to make reusable components in angular? for how child and parent component works.

I will show you this with an example of simple for with parent and child component.

We will understand this by two examples

  1. Share form control group to another component
  2. Access form group using ControlContainer, ControlValueAccessor and AbstractControl(Fullt customizable input)

How to pass form control to child component in angular 12 ?

Step 1: Create a new project

Create a project reusable-component using ng new command.

ng new reusable-component

Step 2: Create Child Component

Create a child component so we can use it in our parent component and as you can see in below code we have added @Input decorator form by which we can accept the form group object from parent component.

ng g c price-input
import { Component, OnInit, Input } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-price-input',
  templateUrl: './price-input.component.html',
  styleUrls: ['./price-input.component.css']
})
export class PriceInputComponent implements OnInit {
  @Input()
  form:FormGroup;
  constructor() { }

  ngOnInit() {
  }

}

and html

<div class="form-input">
    <label>Price</label>
    <input [formControl]="form.get('price')" />
    <span>{{form.get('price').touched &&!form.get('price').valid?"This field is required":""}}</span>
</div>
<div class="form-input">
    <label>Sell Pirce</label>
    <input [formControl]="form.get('sell_price')" />
    <span>{{form.get('sell_price').touched && !form.get('sell_price').valid?"This field is required":""}}</span>
</div>

Generally we user formControlName but here we are using [formControl] input to work with parent form group and form.get() to pass the input reference.

Step 3: Create Parent Component

Now, create a component to handle the form and submission of it. it will create 4 files one ts file, 1 view file , css file and test file.

ng g component product-form

And ProductFormComponent is below, here we will create a form group with 5 inputs

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

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
  form : FormGroup = new FormGroup(
    {
      title:new FormControl("",[Validators.required]),
      email:new FormControl("",[Validators.required]),
      price:new FormControl("",[Validators.required]),
      sell_price:new FormControl("",[Validators.required]),
      author:new FormControl("",[Validators.required]),
      date:new FormControl("",[Validators.required]),
    }
  );
  constructor() { }

  ngOnInit() {
  }

  onSubmit(){
    console.log(this.form.value)
  }

}

and html file for component , here we have used <app-price-input [form]='form' ></app-price-input> as a child component and also passed form group object as a input to this child component

<h2>Product Form</h2>
<form [formGroup]="form" (submit)="onSubmit()">
    <div class="form-input">
        <label>Title</label>
        <input formControlName="title" />
         
        <span>{{form.controls.title.touched &&  !form.controls.title.valid?"This field is required":""}}</span>
    </div>
     
    <div class="form-input">
        <label>Email</label>
        <input formControlName="email" />
        <span>{{form.controls.email.touched && !form.controls.email.valid?"This field is required":""}}</span>
    </div>

    <app-price-input  [form]='form' ></app-price-input>

   <div class="form-input">
        <label>Author</label>
        <input formControlName="author" />
        <span>{{form.controls.author.touched && !form.controls.author.valid?"This field is required":""}}</span>
    </div>
<div class="form-input">
        <label>Date</label>
        <input type='date' formControlName="date" />
        <span>{{form.controls.date.touched && !form.controls.date.valid?"This field is required":""}}</span>
    </div>
      

    <div class="form-input">
       <input type="submit" value="Submit" name='submit' />
    </div>
 
</form>

Now, we can create a separate route or we can call it in app.component.html directly to render it as below

<app-product-form></app-product-form>
Method 2

In this example we will implement a fully customizable input component and will be able to handle all event of form control in component. Only difference in above method and this method is step 2.

Step 1: Create a new project

Create a project reusable-component using ng new command.

ng new reusable-component

Step 2: Create Reusable Child Component

Now, here we are going to create a component with ControlContainer, FormControl, ControlValueAccessor and AbstractControl which handle all events of form control separately.

Before start let me brief you about ControlContainer, FormControl, ControlValueAccessor and AbstractControl

  1. ControlContainer : Base class of NgControl and find the parent form.
  2. FormControl : Keep track of value of form input and validations.
  3. ControlValueAccessor : An interface between Angular form apis and native dom element.
  4. AbstractControl : Base class for FormControl, FormGroup, and FormArray.

Now, create a component using angular cli.

ng g component custom-input
import { Component, OnInit, Input, ViewEncapsulation, forwardRef } from '@angular/core';
import { ControlContainer, FormControl, ControlValueAccessor, AbstractControl, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.css'] ,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ],

})
export class CustomInputComponent implements ControlValueAccessor,OnInit {
  @Input()
  formControlName:string;
  
  control:AbstractControl;

  @Input()
  placeholder:string = '';

  @Input()
  type:string = 'text';

  constructor( private controlContainer: ControlContainer) { }

  ngOnInit() {

    if(this.controlContainer && this.formControlName){
       this.control = this.controlContainer.control.get(this.formControlName);
    }

  }

  registerOnChange(){

  }

  registerOnTouched(){

  }
  writeValue(){

  }
  setDisabledState(){

  }
   


}

Here we have implemented the interface ControlValueAccessor and @Input formControlName .

html for custom input

<div class="form-input">
    <label>{{placeholder}}</label>
    <input [type]='type' [formControl]="control" />
    <span>{{control.touched && !control.valid?"This field is required":""}}</span>
</div>

Step 3: Create Parent Component

Now, create a component to handle the form and submission of it. it will create 4 files one ts file, 1 view file , css file and test file.

ng g component product-form

And ProductFormComponent is below, here we will create a form group with 5 inputs

<h2>Product Form</h2>
<form [formGroup]="form" (submit)="onSubmit()">
    <div class="form-input">
        <label>Title</label>
        <input formControlName="title" />
         
        <span>{{form.controls.title.touched &&  !form.controls.title.valid?"This field is required":""}}</span>
    </div>
     
     

    <app-price-input  [form]='form' ></app-price-input>

    <app-custom-input  placeholder='Email' type='email' formControlName='email'    ></app-custom-input>
    
    <app-custom-input  placeholder='Author' type='text' formControlName='author'    ></app-custom-input>
    
    <app-custom-input  placeholder='Date' type='date' formControlName='date'    ></app-custom-input>
    


    <div class="form-input">
       <input type="submit" value="Submit" name='submit' />
    </div>
 
</form>

Screenshots

Screenshot 2021 12 08 at 1.20.14 PM
Screenshot 2021 12 08 at 1.20.26 PM
Screenshot 2021 12 08 at 1.26.55 PM

Related

Javascript Angular

Post navigation

Previous post
Next post

Related Posts

Javascript How to copy object without reference in angular

How to copy object without reference in angular ?

April 13, 2022April 14, 2022

In this tutorial we will learn to copy object without reference in angular. Objects and array are work on reference by address methodology means Objects and array keeps the address means if you change anything in the object or array from anywhere then it will change the value in original…

Read More
Javascript Remove hash from url in Angular

Remove hash from URL in angular 12 and deploy to server

February 1, 2022

From the first install angular come with hash URL routing and it’s defined in app-routing.module.ts. To remove hash from URL we need to change useHash key to false. Angular runs it development application ng server and whenever we wanted to deploy the application we need a server like Apache or…

Read More
Javascript ngFor and For loop over object or Array in angular

ngFor and For loop over object or Array in angular

March 30, 2022October 4, 2022

Loops are used to iterate through objects or array, In angular we can use ngFor and For loop over array or object in angular, ngFor is a template structural directive which is used to iterate a loop in template file whereas for and each is used to iterate the loop…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version