Creating a Phone Input with Angular

This component will house all of the tooling for the first iterations of our phone number input. Open phone-num.component.ts and import FormControl and AbstractControl:

 import​ { FormControl, AbstractControl } ​from​ ​'@angular/forms'​;

FormControl is the root building block of all reactive forms in Angular. It represents a single input on the page. FormControl objects can be combined together into larger collections of elements, but for now let’s focus on just getting the phone number input working. Used when validating inputs, AbstractControl is a type definition that defines what properties and methods you can access. (AbstractControl covers not only FormControl objects, but also FormGroup and FormArray, which you’ll learn about later in this chapter.) The next step is to create a FormControl property on our controller. Add the following line as a declaration to the PhoneNumComponent class:

 export​ ​class​ PhoneNumComponent ​implements​ OnInit {
  phoneNumber = ​new​ FormControl();
 <div class=​"row"​>
  <div class=​"col-xs-2"​>
  <label for=​"phoneNum"​>Phone Number:</label>
  </div>
  <div class=​"col-xs-10"​>
  <input ​[​formControl​]="​phoneNumber​"​ class=​"form-control"​ id=​"phoneNum"​/>
  </div>
 </div>

Most of the HTML is styling. The important part to look at is <input [formControl]="phoneNumber"/>. This input uses the Angular directive formControl to connect that input to the phoneNumber FormControl property on our component. Changes to this input are reflected in the value of this.phoneNumber.value. So far, so standard. Let’s take a peek behind the curtain to inspect what tooling reactive forms unlocks for us.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.59