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 Customdirective in angular

How to Create Custom Directive in Angular 12?

October 12, 2021February 8, 2024

In this tutorial we will learn to create the custom directive in angular and how to use them in our project. Custom directives are those directives by which we can enhance the html capabilities and can bind custom attributes, methods to it. We can reuse them in any element or…

Read More
Javascript Setup Client side javascript validation

How to Setup Client side javascript validation ?

September 16, 2021September 29, 2021

In this tutorial we will learn javascript validation without using any third party library. we will validate the simple form with 5 inputs fields. Let’s start with simple steps Step 1: Create a html file Firstly we are going to create html file which contains a form with basic fields….

Read More
Javascript how to install angular

What is Angular and how to install angular ?

August 29, 2021October 1, 2021

Angular is a framework of javascript. It’s used for creating efficient and single page application with ease. We can define the angular as follow: Angular is a component based component framework. Angular is collection of libraries which include routing, forms, validations, http requests etc. Angular is easy to use and…

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

  • August 2025
  • July 2025
  • June 2025
  • 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 Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version