DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. FormBuilder in Angular 6

FormBuilder in Angular 6

In this article, see how FormBuilder in Angular makes common web development tasks easier while utilizing reactive programming concepts.

John Vester user avatar by
John Vester
CORE ·
Nov. 13, 18 · Tutorial
Like (3)
Save
Tweet
Share
142.51K Views

Join the DZone community and get the full member experience.

Join For Free

As a follow-up to my "New Application Journey" article, I wanted to focus on how FormBuilder in Angular improves the process of form-based aspects of your application, while introducing some reactive programming concepts along the way.

Recap

As a TL;DR (too long, didn't read) to the original article, I wasn't happy with the application my mother-in-law was using for her very small business in the southeast section of the United States. So, I used her business needs to create a new application from scratch using Angular, MySQL, and the AWS environment. Since the application had a few forms to introduce, I was dreading the dated process I have been using — going all the way back to my introduction to AngularJS back in 2013.

Then, I noticed there was a FormBuilder in Angular, which used reactive programming concepts. This added a new layer of excitement for my new application journey.

What Is Reactive Programming?

According to Wikipedia, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change.

The Wikipedia page provides an example that I always recall when explaining reactive programming to new members of a current project. Typically, when using imperative programming the following line of code might be executed in a method or function:

 a = b + c 

Prior to reactive programming, the variable a would be set to the sum of the current values of b and c at the time the line of code was executed. If later in the method, b  or c changed, the value of a would remain the same.

Reactive programming would consider each variable as a stream, with the concept that a will always equal the sum of b and c. Thus, if b or c changed, the value of a would automatically change.

Angular FormBuilder

When building forms in the current version of Angular there are two options. The first is the typical template-based approach which relies on less explicit, unstructured data model, directives, and asynchronous predictability. The other is a reactive approach which relies on a more explicit, structured data model, functions, and synchronous predictability.

Since I had used the template approach for quite some time, I was excited to try the FormBuilder in a reactive mode. 

A Simple Example

The following screenshot was shared in my original "New Application Journey" article:

Image title

This is a simple form, which has required fields for Property Name, Sales Price, and Commission amount. Since this screen shot was created, we removed the titleDate and only now have a closingDate. The closingDate field is also required, but have a default value that can only be changed and not removed.

I needed to setup the FormBuilder object in Angular.

The constructor of my class included an inject of the FormBuilder class, as shown below:

constructor(private formBuilder: FormBuilder, ...) {
this.createForm();
}

When the constructor fires, the createForm() method is called, which establishes the propertyForm object:

private createForm(): void {
    this.propertyForm = this.formBuilder.group({
      property: this.formBuilder.group({
        propertyName: ['', Validators.required],
        closingDate: '',
        agentSales: '',
        lastName:  '',
        agentInitials: '',
        salesPrice: ['', Validators.required],
        county: '',
        exemptAmount: '',
        baseTax: '',
        surtax: '',
        totalSalesTax: '',
        commission: ['', Validators.required],
        profit: '',
        totalAgentAmount: '',
        referralName: '',
        referralAmount: ''
      }),
      closingDate: ['', Validators.required],
    });
  }

My propertyForm includes a property object, which matches my DTO and a closingDate object — which is used for the NgbDateStruct implementation for the Closing Date field.

To initialize a new property on the form, I called a private method to establish the default values:

private createNewProperty(): void {
    const today = new Date();

    this.property = new Property();
    this.property.propertyName = null;
    this.property.closingDate = today.getTime();
    this.property.salesPrice = null;
    this.property.commission = null;

    this.closingDate = {
      year: today.getFullYear(),
      month: today.getMonth() + 1,
      day: today.getDate()
    };

    this.propertyForm.setValue({property: this.property, closingDate: this.closingDate});

When I need to push values into the FormBuilder object, I use the setValue() or patchValue() methods. When I want to retrieve values from the FormBuilder object, I use the value attributes on the this.propertyForm object.

The biggest challenge I ran into with this form was getting the this.closingDate values into thethis.property.closingDate attribute. The former is a JSON object with attributes for year, month, and day, while the latter is a Date() object.

Looking Ahead

This article is a continuation of a multi-part series that I am putting together regarding my new application journey to providing a better application experience for my mother-in-law. Below, is a list of the current and planned articles, if you are interested in reading more:

  • New Application Journey

  • Okta, a nice solution - even for small apps

  • FormBuilder in Angular 6 (this article)

  • The Challenge of the Commission Report

  • Making the County List Dynamic

  • New Version of the Commission Report

  • What I Learned After Initial Deployment

Have a really great day!

AngularJS application Reactive programming Object (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Continuous Development: Building the Thing Right, to Build the Right Thing
  • The Role of Data Governance in Data Strategy: Part II
  • API Design Patterns Review
  • How to Quickly Build an Audio Editor With UI

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: