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

Uncategorized setup simple jQuery form validation

How to setup simple jQuery form validation?

September 15, 2021September 29, 2021

In this tutorial, we are going to learn jQuery form validation using jQuery validation plugin. this plugin have many features like to validate text, email, phone number , sync Ajax request etc. Let’s begin with step by step guide: Step 1: Create a html file Firstly we are going to…

Read More
Javascript Angular conditional validation in reactive forms

Angular conditional validation in reactive forms

September 26, 2022March 16, 2024

This post covers the basis of angular conditional validation in reactive forms. By the end of this post, the reader will know how to set up a simple form and validate it according to different criteria. Conditional validation is when the validity of a form control is determined by something…

Read More

How to create a service in angular?

September 11, 2021October 3, 2022

Services are same as class with a specific purpose of it. Services can contain method, property and any feature of an application which we can reuse multiple time in our web application. Services also contain a decorator which tell angular how to consume it in our application. Let’s create a…

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

  • 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

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version