Components and Controllers and Contacts

So Angular 2 is pretty cool.  I’m still feeling my way through some parts, but it just seems to make more sense to me than version 1.  Components instead of controllers, sometimes using shared services, reaching out to templates- it’s all good.

We’ve been working on an example form for adding contacts to the new system.  Setting up the form and submitting it was a breeze, though figuring out validation was a bit tricky.  Maybe because of the options- there are 3 or 4 different ways to do it in Angular 2- the one that made the most sense to me is to create a ControlGroup on the component and manage it fully from there.  You can then create individual Controls on each filed to specify what validation you want (and even what initial value you might want for that field).

Though there was one minor thing lacking- there’s no way to reset the form after submission.  You could do a simple form.reset(), but that’s only going to clear the fields, not reset the Angular-driven ControlGroup.

The answer: create a new ControlGroup each time.  First, we added a method to the component- setForm().  This handles all the initialization of our controls:

this.contact_active = new Control(true);
this.contact_name = new Control('', Validators.required);
this.contact_sn = new Control('', Validators.required);

Be sure to use the ‘new’ keyword- we are creating a new object each time this method is called.  Then, we set up the formBuilder group- which acts as a bridge to the actual html form in our template- assigning the validators we created above to the actual fields:

this.newContact = this._formBuilder.group({
  'contact_active': this.contact_active,
  'contact_name': this.contact_name,
  'contact_sn': this.contact_sn
})

Now we just need to call setForm() in the right places inside the component.  Once in the constructor (or ngOnInit if you prefer) to set the initial form.  Then, call it at the end of your method used to actually add the new contact (the call to your backend to save the data).  And boom- you have a reusable form, with validation!

Next week- combining Angular 2 with some traditional Javascript tasks.  We wanted to be able to use checkboxes to delete multiple contacts at once.  Best method?  I have no idea, but we’ll look at our solution!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s