Angular Project Creation:
We can create angular create in 2 Ways.
By using angular cli
1. npm install -g @angular/cli
2. ng new app-demo(application name)
3. cd app-demo
4. ng serve
Note:
ng serve -open(opens directly in the browser)
(or)
ng serve -o(opens directly in the browser)
Customized/manually
Project Explanation:
[Link]
Main Component loads inside the [Link]
Ex:<app-root></app-root>
Component:
We can create in 2 ways.
a. cli
ng g c header(component name)
Note:
g (generate)
c (component)
b. manually
components are 2 types.
1. Main Component
Main Component File Names:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Note:
We no need to create main component.
Main component created at the time of project creation.(ng new app-demo(project name))
2. Child component
Note:
Imp:
Component information [Link]
@Component({
selector: 'app-header',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
@component:decorater
Selector, templateurl, styleurls are metadata.
We load a component by using selector.
Ex:<app-header></app-header>
cli(ng g c header(component name)),
[Link]
[Link]
[Link]
[Link]
[Link] file:
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
SignupComponent,
SigninComponent,
PageNotFoundComponent,
SectionChildComponent,
HomeChildComponent,
ContactUsComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
@NgModule is a decorator
Declaration:[] is used for include components(className)
Imports:[] is used for include modules.
Providers:[] is used for include services.
manually
Routing:
1. Go to [Link]
const routes: Routes = [
{
path:'home',
component:HomeComponent
},
{
path:'Signup',
component:SignupComponent
},
{
path:'Signin',
component:SigninComponent
}
];
2. Go to [Link]([Link])
Add routerLink attribute to the links(li).
Ex:
<li routerLink="home"><a href="">Home</a></li>
<li routerLink="Signup"><a href="">SignUp</a></li>
<li routerLink="Signin"><a href="">Signin</a></li>
3. Load routerLink
Ex:<router-outlet></router-outlet>
How to Install Bootstrap in Angular?
npm install bootstrap
Note: above statement will auto download’s the latest version of Bootstrap.
npm install bootstrap@4(version number)
How to Add Bootstrap in Angular?
By using cdn’s
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FirstAngproject</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
<link rel="stylesheet"
href="[Link]
[Link]">
</head>
<body>
<app-root></app-root>
</body>
</html>
Manually load css and js library file inside [Link]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FirstAngproject</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/[Link]" />
</head>
<body>
<app-root></app-root>
</body>
</html>
By Including in [Link] file
Go to [Link] file select styles and enter the Path’s.
"styles": [
"src/[Link]",
"./node_modules/bootstrap/dist/css/[Link]"
],
"scripts": [
"./node_modules/bootstrap/dist/js/[Link]"
]
How to Transfer the data between the components?
Parent – Child
(@Input)
Note: We need to import @Input at the child component
1. Load the child component inside the parent component.
2. Add @Input decorator variable name(mainTitle) as attribute at the loaded place.
<app-section-child [mainTitle]="title"></app-section-child>
Note: title is a parent component variable.
Child – Parent
(@Output)
Note: We need to import @Output & EventEmitter at the child component
1. Now write a message to send to parent in child [Link].
2. Now create a function in child [Link] and emit it.
3. Call the above function in child [Link].
4. Now go to parent [Link] file & create a variable with some data.
5. In same parent file create a function parameter as $event.
6. Now go to parent html file load the child component inside parent component & now call
the above function with child component variable name (simTitle) as click event at the
loaded place.
7. Now interpolation is done for parent variable (data) in parent html file.
Child – parent:
@viewchild()
[Link] the child component in parent [Link] file.
[Link] go to child [Link] file create a variable.
[Link] go to parent [Link] file import ViewChild& AfterViewInIt.
[Link] same parent [Link] file add @ViewChild(), and pass parameter as child component name
(UserComponent).
[Link] same Parent ts file implement AfterViewInIt in export class.
[Link] call the child variable (childData)in parent ts file in AfterViewInIt().
[Link] in parent ts file create a variable (message) and call it in AfterViewInIt.
[Link] interpolate the parent variable(message) in parent [Link] file.
[Link] in output we get the message but in console we get an error like change was not [Link]
we can remove the error. Go to parent component ts file import ChangeDetectorRef.
10. Now Inside constructor pass the changeDetectorRef as parameter.
[Link] call the ChangeDetection in AfterViewInIt.
Custom directives:
1. Now generate one directive using ng g d custom(directive name).It will generate 2 files.
2. Now go to [Link] file create one h1 element.
3. Now go to [Link] file copy the selector name (appCustom) and add it as a attribute for
[Link] file.
4. Now go to [Link] file in constructor add ElementRef.
5. Now for above constructor add nativeElement and style for it.
Custom pipe:
Syntax: ng g p pipe-name (it will create 2 pipes).
[Link] go to [Link] file in return null place change it to Hello for display
2. Now go to [Link] file create one variable.
3. Now go to [Link] file create h2 element interpolate the above ts variable with
pipe. (test is the pipe name which is used).
Another Example for Custom pipe:
1. Now go to [Link] create one object and one variable.
2. Now go to [Link] file change the transformation.
3. Now go to [Link] file in h2 element interpolate variables with pipe.
Another Example for pipes:
1. Now go to [Link] file and create one variable and reverse it.
2. Now go to [Link] file create one variable.
3. Now go to [Link] file interpolate the variable with pipe.
Simple pipe convertions:
[Link] pipe
Now go to [Link] file create one variable.
Now go to [Link] file create h1 element interpolate above variable with pipe’
Currencypipe:
. For [Link] file
html
Lazy Loading:
Lazy loading means when ever we need a particular component/module in that case we use lazy
loading to load that specified component/ module.
1. First we need create a module using ng g m lazy1 –routing ( --routing gives routing file).
2. Now go to [Link] file in routes array include our module (lazy1) and add
load children.
3. Now create a component inside a lazy1 module (i.e ng g c lazy1/lcom).
4. Now go to [Link] file in array add the lcom component.
Route guard:
1. Can activate 2. Can deactivate 3. Resolve 4. Can load 5. Can activate child
1. Now create a auth guard (ng g g auth) it will create 2 files.
2. Now go to [Link] file implement canactivate in required route.
3. Now go to auth [Link] file in export change true to false to implement our route guard.
Services
We have 2 Types of services.
Built-in Services
Custom Services
We can create in 2 ways:
1. Manually
2. By using cli
ng g s demo(service name)
g – generate
s – service
a. Register your service at higher level ([Link])
Go to [Link] go to inside providers array
Copy the service class name & paste inside the providers array.
b. How to include service in a component?
Go to component & create a constructor method , pass the parameter as service name.
constructor(private _StatesService : StatesService){
HTTP Client Module:
a. We need to import http client module in [Link] file inside imports array
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
SignupComponent,
SigninComponent,
PageNotFoundComponent,
SectionChildComponent,
HomeChildComponent,
ContactUsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CommonModule,
FormsModule,
HttpClientModule
],
b. Go to services & include http client module inside constructor.
constructor(private http:HttpClient) { }
API:
1. Now Go to [Link] & create a variable by assigning a link.
booksApi:string='[Link]
2. Create a function in [Link] & get the http client into it.
getBooksApi(){
return [Link]([Link]);
}
3. Now go to [Link] & include a private key in the constructor.
constructor(private _CountryService:CountryService){}
4. Declare a variable & assign a datatype for it in [Link] under export class.
booksData:any;
5. Create a function in [Link] & fetch the http client from [Link] by subscribing it in
[Link].
fetchBooksApi(){
this._CountryService.getBooksApi().subscribe(res =>
[Link] = res);
[Link]("BooksData:",[Link]);//checking of data in
console
}
6. Now goto [Link] and call the above function in a button to hit the API.
<button (click)="fetchBooksApi()" class="btn btn-
primary">GetAPI</button>
Image:
We can include image in 2 ways.
1. By using src with hardcoded value.
<img src="../../assets/media/[Link]" alt="Dileep picture"
class="profile-picture" />
2. By using property binding.
Go to ts file & declare a variable with value(path).
profileImage:string = '../../assets/media/[Link]';
Go to Html file
<img [src]="profileImage" alt="Dileep picture" class="profile-picture"
/>
Note: By using PropertyBinding
(or)
<img src="{{profileImage}}" alt="Dileep picture" class="profile-
picture" />
Note: By using Interpolation.
Ternary Operator
testData ? ' ' : ' '
testData is a variable.
? is a ternary operator.
‘ ’ (before : ) is a true condition.
‘ ’ (after : ) is a false condition.
Forms:
Reactive Forms (Custom)
Initialization:
1. Import Reactive forms module in [Link]
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutUsComponent,
ContactUsComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CommonModule,
FormsModule,
ReactiveFormsModule
],
2. Now go to [Link] &
a. First create FormGroupName
export class AboutUsComponent implements OnInit{
aboutUsForm!: FormGroup;
b. Now bind the form name to view(HTML).
<form [formGroup]="aboutUsForm">
c. Go to [Link] again & create constructor of FormGroup.
[Link] = new FormGroup({});
Create formControl(Constructor) for each input field.
[Link] = new FormGroup({
nameF: new FormControl('dileep'),
email: new FormControl(),
comments: new FormControl()
});
3. We need to add formControlName attribute for each input because we need to bind ts to
html.
<input type="text" formControlName="name" class="form-control"
id="exampleFormControlInput1" placeholder="name">
Note: FormControlName will be your key which we created inside formGroup in ts page.
Validations:
1. Import FormBuilder & Validators for Validations
import { FormBuilder, Validators } from '@angular/forms';
2. Create constructor & initialize the form Builder.
constructor (private _fb:FormBuilder) {}
3. Create the form group using form Bulider
Note:
Modify the existing formGroup.
[Link] = this._fb.group({})
4. Add the Individual fields for validation.
[Link] = this._fb.group({
nameF: ['dileep',[Link]],
email: ['',[Link]],
comments: ['',[Link]]
});
5. Button validation in html.
<button class="btn" type="submit"
[disabled]="[Link]"
[ngClass]="[Link] ? 'btn-danger' : 'btn-
success'" >Submit</button>
Update:
By using npm Json Server: we will update the data.
1. Install Json Server
npm install -g json-server
2. Create [Link] inside app folder & paste below data.
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
3. Start Json server
json-server --watch [Link]
Create formpost steps:
1. Create a method inside the services to holds the postApi.
aboutUsFormDataPost(data:any){
return
[Link]<any>('[Link]
}
2. Once we create post method by using pipe will filter the data.
return
[Link]<any>('[Link]
3. Pipe will expect map method to holds/structure.
Map is the rxjs operator.
import { map } from 'rxjs/operators';
return
[Link]<any>('[Link]
ny) => {
return res;
}));
4. Go to [Link] & inject the services.
constructor (private _fb:FormBuilder,private
_StatesService:StatesService) {}
5. Create datamodel set.
Goto component folder & create a file ([Link])
export class aboutUsForm {
nameF:string='';
email:string='';
comments:string='';
}
6. Go to service & create a constructor by using data model set.
aboutUsFormObj:AboutUsForm= new AboutUsForm();
7. Assign datamodel keys to form values.
onSubmit(form:FormGroup){
[Link]=[Link];
[Link]=[Link];
[Link]=[Link];
}
8. Subscribe the PostApi
this._StatesService.aboutUsFormDataPost([Link]).subscri
be((res) => {
[Link]("DataUpdate:",res);
alert("data added successfully!");
},
(error)=>{
alert("data not added");
});
Template-driven Forms (Angular Provided / Built-in):
1. First create a form and input fields in [Link] file.
2. For input field add ngModel, name, and assign a varible for ngModel (#un) and add required
and min length.
3. Now go to [Link] file create a function in it and pass parameter as un which is ngModel
vriable name.
4. Now create a button in html component and call the ts function in it.
5. Now go to html check validation for inputfield. Here un is ngModel variable name.
6. Now we need to add colors for input fields like error msg red and success msg green go to
component css file.
7. We need to show total validations in console use ngModelGroup and total code for template
forms. (html)
8. component ts [Link]. [Link]
Binding:
One way Data Binding:
(Model - View)
Note: Property Binding []
Event Binding ()
Ex:
Two way Data Binding:
(Model – View & View - Model)
Angular Life-Cycle hook:
1. ngOnChanges():
ngOnchanges() calls before before ngOnInit().
Respond’s when Angular sets or resets data-bound input properties.
2. ngOnInit():
Initialize the directive or component after Angular first displays.
Sets the directive or component's input properties.
3. ngDoCheck():
Detect and act upon changes that Angular can't or won't detect on its own.
4. ngAfterContentInit():
Respond after Angular projects external content into the component's view
5. ngAfterContentChecked():
Respond after Angular checks the content projected into the directive or component.
6. ngAfterViewInit():
Respond’s after Angular initializes the component's views and child views.
7. ngAfterViewChecked():
Respond’s after Angular checks the component's views and child views.
8. ngOnDestroy():
Cleanup just before Angular destroys the directive or component.
Component Styles:
Synchronous:
Asynchronous:
Pipes: (|)
To transform the data.
We can create by 2 Ways.
1. Built-in
2. Custom
How to call multiple api’s:
Calling multiple APIs in an Angular service can be done in several ways, depending on your
specific requirements. Here's one approach using RxJS Observables and the forkJoin
operator to combine multiple HTTP requests:
1. Import Required Modules: First, make sure you have the HttpClientModule
imported in your Angular app.
2. Create a Service: Create a service (or use an existing one) to handle your API calls.
Let's call it APIService.
3. Define API Methods: Define methods in your service to call each API individually.
4. Use forkJoin to Combine Calls: Use the forkJoin operator from RxJS to execute
multiple HTTP requests simultaneously.
We have three API methods ( getUsers, getPosts, getComments), each
returning an Observable of the HTTP response.
The getAllData method uses forkJoin to combine multiple observables into a
single observable that emits an array of values once all input observables have emitted
their last value.
You can then subscribe to the getAllData method in your component to get the
combined data from all APIs.