Category Archives: Angular

Angular – Routing

Defining routes…

Here’s a complex route definition. You can add more using commas. This route allows an id to be passed to the route. Also a guard is setup allowing access to the controlled. The final element is the component who’s template will be activated:


{ path: 'pets/:id', canActivate: [ petsGuard], canDeactivate: [petsDeactivate], component: PetsComponent }

We can call routes within the application using:

pets

or for a button with variable id:

pets

We can use to tell the template where to display the routed element.

To get the parameter from the route:


import {ActiveRoute} from '@angular/router';

constructor(private route: ActivatedRoute)
{
}

then inside the constructor or onInit use a snapshot or an observable:

   

   let id = +this.route.snapshot.params['id'];

   ...or...

   this.subcription = this.route.params.subscribe(p=>
   {
      let id = +p['id'];  
   }

remember to unsubscribe!

Angular – Form Arrays

We can duplicate form controls or form groups using a form array.

  • Remember to setup a div with a form group when added to the component code.
  • build a function that creates the formgroups:

buildFields(): FormGroup {
return this.fb.group({
field1: '1',
field2: '2'
});
}

Replace the way we were building the fields inside the formgroup with calling the function:



this.customerForm = this.fb.group({
   fields: this.buildFields()
});

Create FormArray and replace the above code with:


this.customerForm = this.fb.group({   
   fields: this.fb.array([this.buildFields()])
});

Define a getter to allow the data to be retrieved:


get fields(): FormArray{
   return this.customerForm.get('fields');
}

where fields is the name of the form item on the html.  We need to add a div..




<[formGroupName]="i">
addField(): void {
   this.fields.push(this.buildField());
}