0% found this document useful (0 votes)
2 views

angular

Uploaded by

NAGENDRA BABU
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

angular

Uploaded by

NAGENDRA BABU
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

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:
Index.html

Main Component loads inside the index.html

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:
app.component.html
app.component.scss
app.component.ts
app.component.spec.ts
app.module.ts
app-routing.module.ts
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 header.component.ts

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
@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)),
header.component.html
header.component.scss
header.component.ts
header.component.spec.ts

app.module.ts 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 app-routing.module.ts

const routes: Routes = [


{
path:'home',
component:HomeComponent
},
{
path:'Signup',
component:SignupComponent
},
{
path:'Signin',
component:SigninComponent
}
];

2. Go to component.html(app.component.html)

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="favicon.ico">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.m
in.css">
</head>
<body>
<app-root></app-root>
</body>
</html>

Manually load css and js library file inside index.html


<!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="favicon.ico">
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap-grid.min.css" />
</head>
<body>
<app-root></app-root>
</body>
</html>

By Including in angular.json file


Go to angular.json file  select styles and enter the Path’s.

"styles": [
"src/styles.scss",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [

"./node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
]

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 component.ts.

2. Now create a function in child component.ts and emit it.

3. Call the above function in child component.html.

4. Now go to parent component.ts 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()

1.Load the child component in parent component.html file.

2.Now go to child component.ts file create a variable.


3.Now go to parent component.ts file import ViewChild& AfterViewInIt.

4.In same parent component.ts file add @ViewChild(), and pass parameter as child component name

(UserComponent).

5.In same Parent ts file implement AfterViewInIt in export class.

6.Now call the child variable (childData)in parent ts file in AfterViewInIt().

7.Now in parent ts file create a variable (message) and call it in AfterViewInIt.

8.Now interpolate the parent variable(message) in parent component.html file.

9.Now in output we get the message but in console we get an error like change was not detected.so
we can remove the error. Go to parent component ts file import ChangeDetectorRef.

10. Now Inside constructor pass the changeDetectorRef as parameter.

11.Now 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 component.html file create one h1 element.

3. Now go to directive.ts file copy the selector name (appCustom) and add it as a attribute for
component.html file.

4. Now go to directive.ts 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).

1.Now go to pipe.ts file in return null place change it to Hello for display

2. Now go to component.ts file create one variable.

3. Now go to component.html 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 component.ts create one object and one variable.

2. Now go to pipe.ts file change the transformation.

3. Now go to component.html file in h2 element interpolate variables with pipe.

Another Example for pipes:

1. Now go to pipe.ts file and create one variable and reverse it.

2. Now go to component.ts file create one variable.

3. Now go to component.html file interpolate the variable with pipe.

Simple pipe convertions:

1.uppercase pipe

Now go to component.ts file create one variable.

Now go to component.html file create h1 element interpolate above variable with pipe’
Currencypipe:

. For component.ts 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 app-routing.module.ts 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 lazy1-routing.module.ts 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 app-routing.module.ts file implement canactivate in required route.

3. Now go to auth guard.ts 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 (app.module.ts)


Go to app.module.ts  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 app.module.ts 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 services.ts & create a variable by assigning a link.

booksApi:string='https://jsonplaceholder.typicode.com/posts';
2. Create a function in services.ts & get the http client into it.
getBooksApi(){
return this.http.get(this.booksApi);
}
3. Now go to component.ts & include a private key in the constructor.
constructor(private _CountryService:CountryService){}
4. Declare a variable & assign a datatype for it in component.ts under export class.
booksData:any;
5. Create a function in component.ts & fetch the http client from services.ts by subscribing it in
component.ts.

fetchBooksApi(){
this._CountryService.getBooksApi().subscribe(res =>
this.booksData = res);
console.log("BooksData:",this.booksData);//checking of data in
console
}
6. Now goto component.html 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/D.Photo.jpg" 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/D.Photo.jpg';
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 app.module.ts

import { FormsModule,ReactiveFormsModule } from '@angular/forms';


@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutUsComponent,
ContactUsComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CommonModule,
FormsModule,
ReactiveFormsModule
],

2. Now go to component.ts &


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 componenet.ts again & create constructor of FormGroup.


this.aboutUsForm = new FormGroup({});

Create formControl(Constructor) for each input field.

this.aboutUsForm = 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.

this.aboutUsForm = this._fb.group({})
4. Add the Individual fields for validation.
this.aboutUsForm = this._fb.group({
nameF: ['dileep',Validators.required],
email: ['',Validators.required],
comments: ['',Validators.required]
});
5. Button validation in html.
<button class="btn" type="submit"
[disabled]="aboutUsForm.invalid"
[ngClass]="aboutUsForm.invalid ? '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 db.json 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 db.json

Create formpost steps:


1. Create a method inside the services to holds the postApi.
aboutUsFormDataPost(data:any){
return
this.http.post<any>('http://localhost:3000/posts',data);
}
2. Once we create post method by using pipe will filter the data.
return
this.http.post<any>('http://localhost:3000/posts',data).pipe();
3. Pipe will expect map method to holds/structure.
Map is the rxjs operator.

import { map } from 'rxjs/operators';

return
this.http.post<any>('http://localhost:3000/posts',data).pipe(map((res:a
ny) => {
return res;
}));
4. Go to component.ts & inject the services.
constructor (private _fb:FormBuilder,private
_StatesService:StatesService) {}
5. Create datamodel set.
Goto component folder & create a file (name-model.ts)

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){
this.aboutUsFormObj.nameF=this.myForm.value.nameF;
this.aboutUsFormObj.email=this.myForm.value.email;
this.aboutUsFormObj.comments=this.myForm.value.comments;
}
8. Subscribe the PostApi
this._StatesService.aboutUsFormDataPost(this.aboutUsFormObj).subscri
be((res) => {
console.log("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 component.html 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 component.ts 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 file.code. css.code


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.

You might also like