angular
angular
Note:
(or)
Customized/manually
Project Explanation:
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
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
2. Go to component.html(app.component.html)
Ex:
Note: above statement will auto download’s the latest version of Bootstrap.
"styles": [
"src/styles.scss",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"./node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
]
4. Now go to parent component.ts file & create a variable with some data.
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()
4.In same parent component.ts file add @ViewChild(), and pass parameter as child component name
(UserComponent).
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.
3. Now go to directive.ts file copy the selector name (appCustom) and add it as a attribute for
component.html file.
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
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 pipe.ts file and create one variable and reverse it.
1.uppercase pipe
Now go to component.html file create h1 element interpolate above variable with pipe’
Currencypipe:
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.
Route guard:
1. Can activate 2. Can deactivate 3. Resolve 4. Can load 5. Can activate child
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
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
SignupComponent,
SigninComponent,
PageNotFoundComponent,
SectionChildComponent,
HomeChildComponent,
ContactUsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CommonModule,
FormsModule,
HttpClientModule
],
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.
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)
Ternary Operator
testData ? ' ' : ' '
testData is a variable.
? is a ternary operator.
Forms:
Reactive Forms (Custom)
Initialization:
1. Import Reactive forms module in app.module.ts
3. We need to add formControlName attribute for each input because we need to bind ts to
html.
Validations:
1. Import FormBuilder & Validators for Validations
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
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)
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)
Event Binding ()
Ex:
Component Styles:
Synchronous:
Asynchronous:
Pipes: (|)
To transform the data.
1. Built-in
2. Custom
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.