Angular Routes and Forms Handson
Angular Routes and Forms Handson
In this course Angular - Routes and Forms, you will learn to:
Creating a Service
Registering Service with Providers.
Defining Service inside constructor of the class that needs the Service.
(Injecting)
Everything looks fine, but what exactly is Service and how do you define it?
What is a Service?
Service is a class that has a specific purpose. Services are mainly used to
provide data to components that ask for it.
Components are used only to provide view to user. The Service class is Decorated
with @Injectable().
It is a parameter decorator
It explicitly tells what are the dependencies of the class inside constructor
parameters
@Injectable()
It is a class decorator
This tells Angular that this class can be used with Dependency Injector. So
whenever a component is dependent on this class, Injector can create the
instance of this class.
@Injectable()
export class SmartPhone{}
------------------
In contact-list.component.ts :
In contact.service.ts :
return of(this.contacts);
-------------------
------------------
HTTP in Angular
Till now you had your data inside Service Class. But in reality, the data is
present in a remote server, which you can get using HTTP calls to APIs.
In Angular you can use HttpClient API to make HTTP requests to backend services.
Observables
Observables are a sequence of values that arrive in asynchronous mode over time.
You can say it works like an array. It is similar to promises in Angular1.x, but
the major difference between Observables and Promises are:
Promise returns only a single value when called once whereas Observables return
multiple values
Observables can be cancelled whereas Promises cannot
Observables Sample
Lets have a look at this sample code to understand how you can create an
Observable in Angular:
init() {
this.data = new Observable(observer => {
setTimeout( () => observer.next(42), 1000 );
}); // this will emit value 42, every 1000ms
Observables In Angular
In case of HTTP request, Observable is a single value (and not sequence of
values) called HTTP Response Object.
To make use of Observables, you use RxJS ( Reactive Extensions for JavaScript).
RxJS is just an external Library to work with Observable.
Few areas in Angular where reactive programming (RxJS) and Observables are used:
EventEmitter, HTTP, Forms.
-----------------
In contact-list.component.ts :
ngOnInit() {
// call your service, and assign its response to contacts variable
this.contactService.getContacts().subscribe(data => this.contacts =
data.contactsList);
}
In contact.service.ts :
return this.http.get<Contacts>(this.url);
-------------------
The PATCH method is used when sending passwords or other sensitive information.
True
----------------
Traditionally websites used to load the whole webpage, on cliking any of the
links. This increases page load time, bandwidth consumption affecting user-
experience
Now you can just load the required view, instead of sending the request to
server to send a whole new webpage
This saves bandwidth, page load time and improves user-experience
The good thing is, you can trace back the history of navigations, and bookmark
paticular view. This is achieved using path, which is visible in the URL
@NgModule({
imports: [ RouterModule.forRoot(appRoutes) ],
})
path: this defines the URL path in your browser address bar
component: this defines which component should be loaded
<nav>
<a routerLink= "/my-cources" > My Cources </a>
<a routerLink= "/explore"> Explore </a>
</nav>
<router-outlet></router-outlet>
Parameterised Routing
In Parameterised Routing, you have a variable in path (url), that accepts
"parameter".
For example, (in Fresco Play) if you click any category, say, Data Science in
Explore, it will show the details of that category and the path can be
---.com/explore/data-science. So you can write routes to look like:
But this could get messy, if we have a lot of categories in Explore. A better
approach can be:
Non-Parameterised Routing
Non-parameterised Routing always has higher priority over "Parameterised"
Routing. Let us consider the example:
Child Routes
In certain scenarios, certain routes should be available only when other routes
are present.
For example you would want SpecficationComponent to load only when a mobile is
selected (--.com/mobiles/423134/spec).
In such scenarios, its better to create them as child routes. The following
video will explain you more about ChildRoutes
---------------
In contacts.component.ts :
In city.component.ts : (same)
ngOnInit() {
// call your service, and assign its response to contacts variable
this.contactService.getContacts().subscribe(data => this.contacts =
data.contactsList);
}
In app.component.html :
<p class="menus">
<span class="menu-item" routerLink= "/contacts"
routerLinkActive="active">Contacts</span>
<span class="menu-item" routerLink= "/cities"
routerLinkActive="active">Cities</span>
</p>
In contact.service.ts :
return of(this.http.get<Contacts>(this.url));
------------
------------
In app.module.ts
import {FormsModule}
@NgModule({
imports: [BrowserModule, FormsModule],
.....
.....
})
ngForm directive gives value of Form Fields. And tells you if the form is in
valid/invalid state
ngSubmit event is fired when a user clicks on Submit button.
ngModel directive creates the FormControl instance to manage the template form
control. It also lets you setup two-way data binding between variable in
component and form-control in template. <input type="text" name="name"
[(ngModel)]="someName">
ngModelgroup directive logically group the form fields under one name. For
example: Street, City, Country, Zip etc can be grouped in Address
Validating TDF
The attributes you use to validate form controls are mostly parts of standard
HTML5 and not angular. For example: required, minlength etc.
Angular provides many classes that are automatically attached to form controls,
but are hidden. You can view them using interpolation {{}} as shown
ng-valid / ng-invalid
ng-untouched / ng-touched
ng-pristine / ng-dirty
@NgModule({
imports: [ ReactiveFormsModule ],
})
All you have to do is import FormBuilder, FormGroup and call .group() method as
shown
In app.component.ts
In app.component.ts
------------
In app.component.ts :
-------------
You can prevent Angular2 from auto-validating the form by using _______.
novalidate
Which of the following will be true if the user changed the value of control?
dirty
------------
Best Practices
Use _(underscore) before a private member and $ after an observable, improves
readability. Example: _courseService , actionSubjects$
One component per file makes it far easier to read, maintain, and avoid
collisions with teams in source control.
Use dashes to separate words in the descriptive name.
Use conventional type names including .service, .component, .pipe, .module,
and .directive.
Use dots to separate the descriptive name from the type. Example: file-
name.component.ts, ----.service.ts etc.
Put bootstrapping and platform logic for the app in a file named main.ts.
Avoid putting app logic in main.ts. Instead, consider placing it in a component
or service.
----------------
Which decorator is optional if the class has any other decorator? @injectable
Which property describes the path you want to redirect the user? redirectTo
You place _______________ where you want the components to be inserted. router-
outlet