Angular Routes and Forms Hands-On Solutions
The main agenda of this solution is those who are unable to do this course due to facing some issues, a little bit of lack of knowledge on these hands-on questions. Try to understand these codes and solve your hands-On Problems. (Not encourage copy and paste these solutions).
The CourseId of Angular Routes and Forms is 55108
1. Dependency Injection in Angular
import { Injectable } from '@angular/core';
import { of, Observable } from 'rxjs';
import { Contacts } from '../models/contacts';
export class ContactService {
contacts = {
'contactsList': [
{'id': 1, 'name': 'Rajesh', 'city': 'bangalore'},
{'id': 2, 'name': 'Aarjith', 'city': 'london'},
{'id': 3, 'name': 'Anjan', 'city': 'california'},
{'id': 4, 'name': 'David', 'city': 'delhi'}
]
};
constructor(
) { }
getContacts(): Observable<Contacts> {
// send contacts to subscriber
return of(this.contacts);
}
}
2.contact-list.component.ts
import { Component, OnInit } from '@angular/core';
import { ContactService } from 'src/app/services/contact.service';
@Component({
selector: 'app-contact-list',
templateUrl: './contact-list.component.html',
styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit {
contacts : any ;
constructor(
private contactService: ContactService
) { }
ngOnInit() {
// get contacts from service and assign it to contacts
this.contactService.getContacts().subscribe( data => {
this.contacts = data ? data.contactsList : [];
});
}
}
2. Http in Angular
1. contact.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Contacts } from '../models/contacts';
// @Injectable({
// providedIn: 'root'
// })
export class ContactService {
url = 'http://www.mocky.io/v2/5c5d880f3200000e11220880';
constructor(
private http: HttpClient
) { }
getContacts(): Observable<Contacts> {
// make http request to the given url and fetch the contacts
return this.http.get<Contacts>(this.url);
}
}
2. contact-list.component.ts
import { Component, OnInit } from '@angular/core';
import { ContactService } from 'src/app/services/contact.service';
import { Contacts } from 'src/app/models/contacts';
@Component({
selector: 'app-contact-list',
templateUrl: './contact-list.component.html',
styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit {
contacts: any;
constructor( private contactService : ContactService
) { }
ngOnInit() {
// call your service, and assign its response to contacts variable
this.contactService.getContacts().subscribe( data => {
this.contacts = data ? data.contactsList : [];
})
}
}
3. app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { ContactService } from 'src/app/services/contact.service';
import { AppComponent } from './app.component';
import { ContactListComponent } from './components/contact-list/contact-list.component';
@NgModule({
declarations: [
AppComponent,
ContactListComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [ContactService],
bootstrap: [AppComponent]
})
export class AppModule { }
3. Routing Angular
1. app.component.html
<p class="title"> Contact Applications </p>
<!-- redirect the following links to appropriate routes -->
<p class="menus">
<a routerLink="/contacts" > <span class="menu-item" routerLinkActive="menu-item-active" id="contact-link"> Contacts </span> </a>
<a routerLink="/cities" > <span class="menu-item" routerLinkActive="menu-item-active" id="cities-link"> Cities </span> </a>
</p>
<div *ngFor = "let c of contacts">
<h3> {{ c.city}} </h3>
<p> {{c.name}} </p>
</div>
<router-outlet></router-outlet>
2. app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContactsComponent } from './components/contacts/contacts.component';
import { CityComponent } from './components/city/city.component';
export const routes: Routes = [
{path:'contacts',component:ContactsComponent},
{path:'cities',component:CityComponent}
];
@NgModule({
imports: [RouterModule.forRoot([])],
exports: [RouterModule]
})
export class AppRoutingModule { }
3. contact.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Contacts } from '../models/contacts';
import { Observable, of } from 'rxjs';
// @Injectable({
// providedIn: 'root'
// })
export class ContactService {
url = `http://www.mocky.io/v2/5c5d880f3200000e11220880`;
constructor( private http:HttpClient
) { }
getContacts(): Observable<Contacts> {
return this.http.get<Contacts>(this.url);
// get contacts from the above url
// const contacts = this.http.get<Contacts>(this.url);
//return of(this.contacts);
}
}
4.city.component.ts
import { Component, OnInit } from '@angular/core';
import { ContactService } from 'src/app/services/contact.service';
import { Contact, Contacts } from 'src/app/models/contacts';
@Component({
selector: 'app-city',
templateUrl: './city.component.html',
styleUrls: ['./city.component.css']
})
export class CityComponent implements OnInit {
contacts: Contact[] = [];
constructor( private contactService : ContactService
) { }
ngOnInit() {
// call your service and assign response to contacts
this.contactService.getContacts().subscribe( data => {
this.contacts = data ? data.contactsList : [];
})
}
}
5. contacts.ts (Interface already in that)
export interface Contacts {
contactsList: Contact[];
}
export interface Contact {
id: number;
name: string;
city: string;
}
4.Angular Reactive Forms question
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
/** create a form (contactForm) with following controls/groups and validations
* - name: control, valiations: required
* - phone: control, validations: required, number of 10 digits
* - address: group
* - street: control
* - city: control
* - zip: number of 6 digits
*/
contactForm = new FormGroup({
name: new FormControl(null,[
Validators.required]),
phone: new FormControl(null,[
Validators.required,
Validators.pattern("^[0-9]*$"),
Validators.minLength(10),
Validators.maxLength(10)]),
address: new FormGroup({
street: new FormControl(null),
city: new FormControl(null),
zip: new FormControl(null,[
Validators.minLength(6),
Validators.maxLength(6),
Validators.pattern('^[0-6]*$')])
})
});
onSubmit() {
console.log('form value =>', this.contactForm.value);
}
get name() { return this.contactForm.get('name'); }
get phone() { return this.contactForm.get('phone'); }
get zip() { return this.contactForm.controls['address'].get('zip'); }
}
Thank-You
// This should be the code for contacts.component.ts
ReplyDeleteimport { Component, OnInit } from '@angular/core';
import { ContactService } from '../../services/contact.service';
import { Contacts, Contact } from 'src/app/models/contacts';
@Component({
selector: 'app-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.css']
})
export class ContactsComponent implements OnInit {
contacts: Contact[] = [];
constructor( private contactService : ContactService
) { }
ngOnInit() {
// call your service and assign response to contacts
this.contactService.getContacts().subscribe( data => {
this.contacts = data ? data.contactsList : [];
})
}
}
Routing Angular is getting failed , can anyone help with that
ReplyDeletein contacts.component.ts add this :
ReplyDeleteexport class ContactsComponent implements OnInit {
contacts: Contact[];
constructor( private contactService : ContactService
) { }
ngOnInit() {this.contactService.getContacts().subscribe( data => {
this.contacts = data ? data.contactsList : [];
})
}
}
npm ERR! Test failed. See above for more details.
ReplyDeleteGetting these errors in Routing in Angular
Click on Install and Try Again
DeleteI am also getting the same error...i have tried more than three times but still getting the same error
DeleteIt is showing that app component is not navigating to cities and contact
ReplyDelete✖ should navigate to /cities when clicked on Cities link
ReplyDelete✖ should navigate to /contacts when clicked on Contacts link
This test cases are failing with the above routing in angular code
npm version related problem, how to solve? ,try 2 3 time
ReplyDeletenpm ERR! Test failed. See above for more details.
test cases are not passed - router assignment
ReplyDeleteContactsComponent
ReplyDeleteX shoue get data in contacts, from server, after component is initialized
X hould calgetContacis) atleast once
X shoula display all centaces in the template using sp eiement
//This should be app.component.ts
ReplyDeleteexport interface Contacts {
contactsList: Contact[];
}
export interface Contact {
id: number;
name: string;
city: string;
}