1566807543
;Most of the code is written in html template file, making it sometimes difficult to understand and test.
There are few benefits of using reactive form over the template forms. These are:
To start with reactive form programming, you should know about these classes:
ng new reactiveform> ng new reactiveform> ng new reactiveform### Add the ReactiveFormsModule in the Module file
In order to use Reactive Forms in your app, we have to first import ReactiveFormsModule
inapp.module.ts
from@angular/forms
, and then add in the @NgModule
imports array.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Let’s first create ourgeneralInfocomponent in the app.
ng new reactiveform
To create any form control, we first have to import FormControl from@angular/forms
package into our component.
import { FormControl } from '@angular/forms';
After importing FormControl, we will create an instance of our form control firstName.
firstName = new FormControl('');
We can use the FormControl constructor to set the initial value of the control. Here, we are setting the empty string in the constructor.
After creating our first form control firstName
in the controller file, it’s time to place this control in our html template file. Let’s put our form control in template.
<label>
FirstName : <input type="text" [formControl] = "firstName">
</label>
Using the template binding syntax, we bind our form control to the firstName
input box in the template.
In order to display our component in the browser window, we are going to place it in the app.component.html
file.
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<app-general-info></app-general-info>
<router-outlet></router-outlet>
Notice line 7, we have placed our component <app-general-info></app-general-info>
in this template. Now, let’s see how our form looks like in browser window.
In reactive forms, you can access any form control state and value at any point of time. You can then manipulate the form control values from the component class or component template. Let’s see how to display our form control value in component template file.
You can access and display the form control value using the value
property.
<p>First Name: {{firstName.value}}</p>
The value on the form will change as you type in the form input control firstName
.
As you can see in above screenshot, as we type zeptobook
in our form control firstName, it is immediately displayed below.
Like you access form control value in component template file, you can access it in component class programmatically. You can manipulate value here in component class file.
ng new reactiveform
Let’s see how to set the control value programmatically. In thegeneral-info.component.ts
file, we have a methodupdateFirstName()
, and set the form control value ZeptoBook usingthis.firstName.setValue('ZeptoBook')
.
updateFirstName(){
this.firstName.setValue('ZeptoBook');
}
Now, we have to write code to call this method from button click event. Let’s create a button and attach updateFirstName() method to button’s click event.
<p>
<button (click)="updateFirstName()">Update First Name</button>
</p>
Now, when user click on this button, it will set the form control value to ZeptoBook
and update this in input box and label.
We can also set some initial value while creating the form control. Remember, we put empty string while creating our firstName form control. Now, let’s see how to use form control constructor to initialize the value in the form control.
age = new FormControl(18);
Here, we have created an age form control and initialized its value to 18 in its constructor. Accessing the age form control in the component template file.
<label>
Age : <input type="text" [formControl] = "age">
</label>
<p>Age: {{age.value}}</p>
Now, open the browser and see the output.
Here you can see, Age
input box and label is showing the initialized value of 18, which you can change anytime.
Now, let’s have a look at complete code.
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-general-info',
templateUrl: './general-info.component.html',
styleUrls: ['./general-info.component.css']
})
export class GeneralInfoComponent implements OnInit {
constructor() { }
ngOnInit() {}
firstName = new FormControl('');
age = new FormControl(18);
updateFirstName(){
this.firstName.setValue('ZeptoBook');
}
}
<p>
Our General Info Component
</p>
<label>
FirstName : <input type="text" [formControl] = "firstName">
</label>
<p>First Name: {{firstName.value}}</p>
<p>
<button (click)="updateFirstName()">Update First Name</button>
</p>
<label>
Age : <input type="text" [formControl] = "age">
</label>
<p>Age: {{age.value}}</p>
Above we read about basic form control, now let’s move forward to group of form controls called FormGroup
. FormGroup is used to track the value and validation state of form control.
ng new reactiveform
Let’s create a new componentapp-form-group
to demonstrate FormGroup.
ng generate component formGroup
After generating our new component, it’s time to import these classes in component class.
import { FormGroup, FormControl } from '@angular/forms';
Let’s create a property in our component class called sampleForm
and set the property to a new Form Group instance. In the Form Group instance constructor, we have created these form control instances.
form control instances in form group
sampleForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormControl(''),
city: new FormControl('')
});
Once we created sampleForm control in component class, it’s time to bind FormGroup model to our component view template.
Let’s see the syntax how to bind the model to view.
<form [formGroup] = "sampleForm" (ngSubmit)="onSubmit()">
<label>First Name: <input type="text" formControlName="firstName"></label><br/>
<label>Last Name: <input type="text" formControlName="lastName"></label><br/>
<label>Address: <input type="text" formControlName="address"></label><br/>
<label>City: <input type="text" formControlName="city"></label><br/>
<br/>
<button type="submit">Submit</button>
</form>
We have add a submit button, and add ngSubmit
event. On pressing submit event, we are firing onSubmit()
function of the component class. Let’s see the complete code.
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-form-group',
templateUrl: './form-group.component.html',
styleUrls: ['./form-group.component.css']
})
export class FormGroupComponent implements OnInit {
constructor() { }
ngOnInit() {}
sampleForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormControl(''),
city: new FormControl('')
});
onSubmit(){
console.log(this.sampleForm.value);
}
}
<p>
form-group works!
</p>
<form [formGroup] = "sampleForm" (ngSubmit)="onSubmit()">
<label>First Name: <input type="text" formControlName="firstName"></label><br/>
<label>Last Name: <input type="text" formControlName="lastName"></label><br/>
<label>Address: <input type="text" formControlName="address"></label><br/>
<label>City: <input type="text" formControlName="city"></label><br/>
<br/>
<button type="submit">Submit</button>
</form>
Also, in order to display this component in browser, I have commented our previous component app-general-info
, and placed our app-form-group
component. See the commented line 7.
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<!-- <app-general-info></app-general-info> -->
<app-form-group></app-form-group>
<router-outlet></router-outlet>
Now, once you open your browser, and see the screen, it looks like this.
On submit, output will be rendered in browser console.window.
Now, see the red marked area in console log.
When we have multiple forms, then it become very tedious and repetitive to create form controls. FormBuilder service is a easy way for generating form controls.
Let’s create a new component app-form-group
to demonstrate FormGroup.
ng new reactiveform#### Import FormBuilder
After generating our new component, it’s time to import these FormBuilder
in component class.
import { FormBuilder } from '@angular/forms';
constructor(private fb: FormBuilder) { }
Here we are going to create a simple login form, having username and password form controls in component class.
builderForm = this.fb.group({
userName: [''],
password: ['']
});
Now, notice the syntax, the declaration of FormGroup
and FormControl
are now implicit. This saves a lot of our code. We only need to have fields name with the default values.
<p>
form-builder works!
</p>
<form [formGroup]="builderForm" (ngSubmit) = "login()">
<label>User Name: <input type="text" name="username" id="username" formControlName="userName"></label><br/>
<label>Password: <input type="password" name="password" id="password" formControlName="password"></label><br/>
<button type="submit">Submit</button>
</form>
If you see, we have a submit button, and attached login()
function to this submit button. See the login() function in the component class file.
login(){
console.log(this.builderForm.value);
}
Add this component in app.component.html
file
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<!-- <app-general-info></app-general-info> -->
<!-- <app-form-group></app-form-group> -->
<app-form-builder></app-form-builder>
<router-outlet></router-outlet>
Open the browser, and see the result.
See the red marked console log. You can see the username and password fields values. The complete code is:
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-form-builder',
templateUrl: './form-builder.component.html',
styleUrls: ['./form-builder.component.css']
})
export class FormBuilderComponent implements OnInit {
constructor(private fb: FormBuilder) { }
ngOnInit() {}
builderForm = this.fb.group({
userName: [''],
password: ['']
});
login(){
console.log(this.builderForm.value);
}
}
<p>
form-builder works!
</p>
<form [formGroup]="builderForm" (ngSubmit) = "login()">
<label>User Name: <input type="text" name="username" id="username" formControlName="userName"></label><br/>
<label>Password: <input type="password" name="password" id="password" formControlName="password"></label><br/>
<button type="submit">Submit</button>
</form>
In this way, we created our simple form using the FormBuilder.
In this post, we learned about reactive form programming using the FormControl, FormGroup and FormBuilder. These are more powerful way of creating forms as compared to template driven approach. You can do lot of things in the component class file, making the component template file light and thin, containing only html syntax. This approach is also useful for testing purpose.
I hope you enjoyed more reading this blog.
Further reading:
☞ The Pros and Cons of Angular Development
☞ Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular
☞ Angular 8 - Reactive Forms Validation Example
☞ Angular vs React vs Vue: Which is the Best Choice for 2019?
☞ A comparison between Angular and React
☞ Getting Started with Nx in Angular
☞ Learn Angular 8 from Scratch for Beginners
☞ How to create a registration form using Angular 8 and Kendo UI
☞ Top 15 Programming Languages by Popularity (2004-2019)
#angular #angular-js
1595344320
Corona Virus Pandemic has brought the world to a standstill.
Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.
Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!
And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!
If you are still not aware of it, don’t worry as Georgia Byng has well said,
“No time is better than the present”
– Georgia Byng, a British children’s writer, illustrator, actress and film producer.
No matter if you are a developer (be it front-end or back-end) or a data scientist, tester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.
From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.
Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.
These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.
Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).
xlr8rs make your development real fast by just adding your core business logic to the template.
If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂
To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.
Since we believe:
“There’s always a scope of improvement“
If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.
#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade
1608866530
Reactive form validation in Angular 11 app. In this tutorial, i will show you how to use reactive form validation in angular 11 app.
As well as, and you will learn how use reactive form validation in angular 11. And also use reactive form with formGroup for validation in angular 11 app.
Reactive Form Validation In Angular 11
Step 1 – Create New Angular App
Step 2 – Import Form Module
Step 3 – Add Code on View File
Step 4 – Use Component ts File
Step 5 – Start Angular App
https://www.tutsmake.com/angular-11-reactive-forms-validation-tutorial-example/
#reactive form validation in angular 11 #angular 11/10/9/8/7 reactive forms validation example #angular 11 form validation example
1596850980
Have you ever wondered why Angular is so powerful with forms? In this article, I will walk you through this topic to understand why and how Angular is better with forms compared to React or Vuejs.
Contents:
Angular provides 2 ways to work with forms which are template-driven form and reactive form.
While template-driven form is dealing with form by using directives, Reactive form allows Angular developers to handle forms at the Angular template component.
Reactive Form will bring more benefits compared to template-driven from such as:
There are 3 fundamental building blocks of Angular Reactive Form:
When we build reactive forms in Angular, they all come from these three basic blocks.
In order to use Reactive Form, import [_ReactiveFormsModule_](https://angular.io/api/forms/ReactiveFormsModule)
from the_@angular/forms_
_ package and add it to your NgModule’s _imports_
array._
Initializing Form Controls
Here is how we create form control in Angular with 4 different syntaxes.
First, we can init form control with value only.
#angular #javascript #reactive-programming #programming #reactive-forms
1599478860
Angular 7 Forms Tutorial Example is today’s leading topic. For this example, we will use Reactive forms. Reactive forms provide the model-driven approach to handle the form inputs whose values are changing over time. Reactive forms use the specific and immutable approach to managing the state of the form at the given point of time. Each change to the form state returns the new state, which maintains the integrity of a model between the changes. Reactive forms also provide the straightforward path to testing because you are assured that your data is consistent and predictable when the request has been made.
Let us install Angular 7 using Angular CLI using the following command.
#angular #angular cli #angular 7 #reactive forms
1608113009
What is new in New Angular 7? New Angular 7 features have turned out as a powerful release that really brought advancement in the application development structure.
Here, we have listed new Angular 7 features with examples and write the difference between Angular 6 and Angular 7.
Read more: Angular 7 Features With Example
#angular 7 features #what’s new angular 7 #new angular 7 features #angular 7 features with examples