How to force the router in angular to always reload when the page is called again…
@ngModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})], exports: [RouterModule], })
How to force the router in angular to always reload when the page is called again…
@ngModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})], exports: [RouterModule], })
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!
We can duplicate form controls or form groups using a form array.
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{ returnthis.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()); }
List of transformations: https://GitHub.com/ReactiveX/rxjs/tree/master/src/operator
Examples:
We use this by adding like so:
import 'rxjs/add/operator/debounceTime' myControl.valueChanges.debounceTime(2000).subscribe(v => this.message(message));
Angular Reactive Forms can manage changes from the user via events in the code. This can enable us to change validation rules, display messages, change user interface elements or much more..
Here’s an example of adding a notification based on a value change. This one is setup from within OnInit:
this.customerForm.get('note').valueChanges.subscribe(value => this.setNotify(value));
We can move validation messaging from the html into the component code allowing us a lot more flexibility.
const myControl = this.customerForm.get('group.myControl'); myControl.valueChanges.subscribe(value => { this.setMessage(myControl); });
setMessage(c: AbstractControl) : void { this.message = ''; if((c.touched || c.dirty) && c.errors) { this.message = Object.keys(c.erros).map(key => this.validation<essages[key]).join(' '); } } });
HTML:
We can use basic validation in html…
..you can see that the field is required and must be 3 characters minimum length.
This and more complex validators can be defined in the code instead making the system more flexible..
import { Component, OnInit } from '@angular/core' import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms' export class OurComponent implements OnInit { customerForm: FormGroup; customer: Customer = new Customer(); constructor(private fb: FormBuilder) { } ngOnInit(): void { this.customerForm = this.fb.group({ firstName: ['default',[Validators.required, Validators.minLength(3)]] }); } }
This might not look very exciting as we’ve just moved the validation from the Template to the code but as we add more validators and more complex validation we start winning bigger.
We can use formbuilder rather than declaring each component and form group new ourselves.
This relies on us adding the import “FormBuilder from @angular/forms
We then use this by utilizing the constructor:
import { Component, OnInit } from '@angular/core' import { FormGroup, FormControl, FormBuilder } from '@angular/forms' export class OurComponent implements OnInit { customerForm: FormGroup; customer: Customer = new Customer(); constructor(private fb: FormBuilder) { } ngOnInit(): void { this.customerForm = this.fb.group({ firstName: 'default' }); } }
or instead of “firstName: ‘default'” you could use “firstName: {value: ‘default’, disabled: false}” this allows you to pass an initial state to the item. Maybe more importantly we can use an array syntax instead which allows us to pass in validators i.e. firstName: [‘default’, [Validators.required]]. In this final example we are using one of the angular built in validators but we can also define and use our own. As you can see this can be an array of multiple comma separated validators.
There are two types of form you can use with Angular “Template driven” and “Reactive” (also known as “Model driven”).
Template driven forms rely on the html to deal with the majority of the form building. See below for a Template driven form. This binds a property from our component class to the value of the input element. You must have a name element in order for this to work effectively. #firstNameVar is the template reference variable to access the form control instance this allows for some error validation. Angular does a lot of our work for us in the template driven approach however it is less flexible. NgModel gives us the two way binding.
The second type of form in Angular is the Reactive form. In this approach we create the form module (which angular deals with under the hood in the Template based approach.
Component:
import { Component, OnInit } from '@angular/core' import { FormGroup, FormControl } from '@angular/forms' export class OurComponent implements OnInit { customerForm: FormGroup; customer: Customer = new Customer(); ngOnInit(): void { this.customerForm = new FormGroup({ firstName: new FormControl('default') }); } }
Remember to add ReactiveFormsModule to the declarations of the Module!
Creating the Reactive Form:
We can now use the formgroups get method i.e. customerForm.get(‘firstName’).valid in the html.
You may need to trust a URL first, otherwise the DomSanitizer will remove it (see the docs).
url = sanitizer.bypassSecurityTrustUrl('data:image/jpeg;base64,' + image)
Then you can use that url and bind it:
.
There a many premade Angular tools out there. For instance the DevExtreme tool kit which can be found here: https://js.devexpress.com/.
Here’s an example of using it for creating a table: