0% found this document useful (0 votes)
3 views13 pages

Angular 14 Typescript Component Basics

The document provides a comprehensive overview of Angular, covering its core concepts such as components, services, decorators, and routing. It explains how to create and manage Angular projects, including generating components, services, and modules, as well as making HTTP requests. Additionally, it highlights the differences between Observables and Promises, and discusses the use of pipes for data formatting.

Uploaded by

mukesh pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

Angular 14 Typescript Component Basics

The document provides a comprehensive overview of Angular, covering its core concepts such as components, services, decorators, and routing. It explains how to create and manage Angular projects, including generating components, services, and modules, as well as making HTTP requests. Additionally, it highlights the differences between Observables and Promises, and discusses the use of pipes for data formatting.

Uploaded by

mukesh pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basics

Q: Which language is used in Angular?


A: Typescript is used to write code in Angular.

Q: Which files are generated when you compile the Typescript file?
A: Javascript files are generated.

Q: How do you use typescript in HTML pages?


A: Typescripts are compiled and converted into JavaScript. We use generated JavaScript in our HTML.

Q: Which architecture is used by Angular 14?


A: Angular uses component-service architecture.

Q: What is a component?
A: For one UI screen we create one component. The component contains View HTML, Controller .TS file, .CSS file and Unit
test case.

Q: What is contained by .ts file in the component? OR what is done by .ts file?

A:

1. It plays the role of the controller.


2. It contains data and action methods.
3. Data is bound with HTML form elements. Action methods are bound with form events.
4. Action methods are called on form events. Action methods perform business operations with help of service classes
and navigate control to the next page.

For example LoginComponent contains [Link] and [Link] data that is bound with HTML form and signin() action
method that performs authentication.

Q: What is contained in the .html file in the component? Or what is done by .html file.
A: It contains HTML view and HTML forms to get input from User. HTML contains view logics

Q: What is a Service?
A: Service is a reusable class, it contains business logic and data. Service generally has REST endpoints and makes
asynchronous (AJAX) calls to web services.

Q: What is a decorator
A: Decorators are annotations. Decorator @NgModule, @Component, @Injectable are used to make modules, components,
and services respectively. Other decorators are @Pipe etc.

Q: Which architecture is followed by a Component


A: A component follow MVC architecture

Project Source Code


Q: How do you configure/generate an Angular project?
A: We generate an angular project using “ng new project-name” command at the console.

Q: How do you create and deploy your project?


A: we generate a build using "ng build --base-href /ContextPath/" command. It will generate build files in the \dist
(distribution) folder. Then these files are deployed on any web server.

Q: How do you run your project?


A: Using “ng serve” or “ng s” command.

Q: What is the folder structure of your project?


A: It generates a folder with the project-name and inside this folder, it generates many subfolders like:

1. C:\project-name\e2e - End to End test cases are contained by this folder


2. C:\project-name\node_modules - Contains dependent NPM modules
3. C:\project-name\src - Cotains application source code
Folder \src contains our developed source code.

Q: In which folder your components are generated?

A: Our components are generated in \src\app folder.

Q: Can you create your components/ services/ pipe etc. manually?

A: Yes, we can create components/ services/pipes manually. We have to make entries of manually created components in the
[Link] configuration file.

Q: Which is the configuration file of your project?

A: An Application is a Module for Angular. The project generates the [Link] configuration file in \src\app folder.

Components, Routers, Services, and Dependent Modules are imported and configured in this file.

Q: Which is the root component of your application?

A: AppComponent is the root component of the application. The project generates [Link] file which contains root
component class.

Q: What is single page application (SPA)


A: SPA loads only single HTML page in its lifetime. On navigation, only part of the HTML page is loaded using AJAX calls.

Q: How do you make a SPA (Single Page Application) in Angular.

A: We make SPA with help of routes and <router-outlet> tag. We define routes for generated components in router file and
use <router-outlet> tag inside AppComponent HTML page.

Q: How do you define routes?

A: Project generates [Link] file. In this file, we define routes for our components.

@NgModule({
imports: [[Link]( [{path:'login', component: LoginComponent},{ path: 'welcome
', component: WelcomeComponent}])],
exports: [RouterModule]
})

export class AppRoutingModule {}

Q: How do you generate a Component?

A: We generate a component using “ng generate component Login” or “ng g c Login” command.

Q: Which decorator is used to define a Component?

A: Decorator @Component is used define a component.

@Component({..})
export class AppComponent {}

Q: How do you generate a Service?

A: We generate a service using “ng generate service User” or “ng g s User” command.

Q: Which decorator is used to define a Service?

A: Decorator @Injectable is used to define a service.

@Injectable()
export class MarksheetService {}

Q: How do you generate a Pipe?

A: We generate a pipe using “ng generate pipe Rs” or “ng g p Rs” command.

Q: Which decorator is used to define a Pipe?

A: Decorator @Pipe is used to define a pipe.

@Pipe ({ name : 'rs' })


export class RsPipe implements PipeTransform {}

Q: How do you generate a Directive?

A: We generate a directive using “ng generate directive FileUpload” or “ng g d FileUpload” command.

Q: Which decorator is used to define a Directive?

A: Decorator @Directive is used to define a pipe.

@Directive({})
export class MyDirDirective {}

Q: How do you generate a Module?

A: We generate a module using “ng generate module MyModule” or “ng g m MyModule” command.

Q: Which decorator is used to define a Module?

A: Decorator @NgModule is used to define a Module.

@NgModule({..})
export class AppModule {}

Component
Q: What is a component?

A: For one UI screen we create one component. Component contains View HTML, Controller .ts file, .CSS file, and Unit test
case.

Q: What is contained by .ts file in the component? OR what is done by .ts file?

A:

1. It plays the role of controller.


2. It contains data and action methods.
3. Data is bound with HTML form elements. Action methods are bound with form events.
4. Action methods are called on form events. Action methods performs business operations with help of service classes
and navigate control to the next page.

For example, LoginComponent contains [Link] and form. password data that is bound with HTML form and signin() action
method that performs authentication.
Q: What is contain by .html file in component? Or what is done by .html file.

A: It contains html view and html forms to get input from User. HTML contains view logics

Q: How do you generate a Component?

A: We generate a component using “ng generate component Login” or “ng g c Login” command.

Q: Which decorator is used to define a Component?

A: Decorator @Component is used to define a component.

@Component({..})
export class AppComponent {}

Q: Can you create your components manually?

A: Yes, we can create components manually. Component entry is made in the configuration file [Link] inside the
declarations array.

Q: How do you map CSS and HTML templates with components?

A: We map CSS and HTML Template using styleUrls and templateUrl attributes of decorate @Component.

@Component({
selector: 'app-login',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})

Q: Which interface will you implement to create a component class?

A: We will implement OnInit interface and define ngOnInit method to create a component. Method ngOnInit is called at the time
of component instantiation.

export class LoginComponent


implements OnInit {
ngOnInit() {
}
}

Q: How do you inject a service into a component?

A: We will inject services using constructer parameters of component class.

constructor( private aroute: ActivatedRoute, private router: Router, privateservice:Marksheet


Service) { }

Q: Can you inject one service into multiple components?

A: Yes, we can inject one service into multiple components. Services are created to be used by multiple components.
Q: How do you read URI variables in a component?

A: URI variables are read by ActivatedRoute service. a [Link] method is called to read url parameters.

constructor(private aroute:ActivatedRoute) { }
ngOnInit(){
let id =[Link]("id");
}

We are assuming that id is passed as part of URI [Link]

Q: Why do you use URI variable in your application?

A: We use URI variable in our application to pass the primary key to the component to edit a record.

Q: How do you do one-way data binding


Ans:
With the help of interpolation and property binding.

//Interpolation
{{name}}

//Property binding
<input value=[name] >

Q: How do you do two-way data binding


Ans:
With the help of ngModel directive, property binding using [] brackets and, event binding using () brackets
<input [(ngModel)] ="userid">

Q: How do you do event handling?


A: with the help of parenthesis and event name inside parenthesis.
<input (click) ="login()">

HTTP
Q: What is a callback function?
A: A function is passed to another function that is called later in time, it is called a callback function.

Q: How do you make AJAX calls to an HTTP Server

A: We use HttpClient service in angular to make AJAX calls.

Q: How do you call RESTFul web services from angular?

A: We use HttpClient service to call RESTful apis.

Q: Which module will you import to use HttpClient service?

A: We import HttpClientModule in [Link] configuration file to use HttpClient .

Q: Which methods are contained by the HttpClient service?

A: HttpClient service contains get(), post(), put(),patch(), delete() methods to make http calls.

Q: What are the differences between HTTP GET and POST methods?

A: GET sends data as a query string whereas POST sends data as a request body.

Q: Which parameters will be passed to HttpClient methods?

A:
1. Method get(url) and delete(url) receive one parameter; url (endpoint)
2. Method put(url,data), post(url,data) and patch(url,data) receive two parameters; url and data.
3. Usually data is a JSON object.

Q: What is httpOptions object? How do you pass header information to get and post methods?

A: Object HttpOptions contains request header information, query parameters, and other configurable values.

All HttpClient methods receive “httpOptions” as the last optional parameter.

1. get(url [,httpOptions])
2. delete(url[,httpOptions])
3. put(url,data[,httpOptions])
4. post(url,data[,httpOptions])
5. patch(url,data[,httpOptions])

Q: What is returned by get() and post() methods?

A: Both methods return an Observable object.

Q: How do you get response data from an observable object?

A: Observable object subscribes to two callback methods, success(response) and fail(response). Both callbacks receive server
response as a parameter.

1) Success-callback is called when the server returns a response


2) If the server is down or the server does not return a response, then the fail-callback is called.

[Link](url).subscribe(function success(res) {
[Link]("Success", res);
},
function fail(res) {
[Link]("Fail",[Link]);
});

PIPE
Q: Why do you use Pipe?

A: Pipes are used to format the data. Pipes can be used to change data from one format to another

{{name | uppercase }} // convert name to uppercase


{{name | lowercase }} // convert name to lower case

Q: Give me names of pipes?

Ans:

1. DatePipe: Formats a date value according to locale rules.


2. UpperCasePipe: Transforms text to all upper case.
3. LowerCasePipe: Transforms text to all lower case.
4. CurrencyPipe: Transforms a number to a currency string, formatted according to locale rules.
5. DecimalPipe: Transforms a number into a string with a decimal point, formatted according to locale rules.
6. PercentPipe: Transforms a number to a percentage string, formatted according to locale rules.

Q: Can you create a custom pipe?

A: Yes, we can generate a custom pipe using “ng g p pipe-name” command.

Q: Which decorator will you use to create Pipe?

A: We use @Pipe decorator

Classes and Object


Q: How do you create a class?

A: We create a class using 'class' keyword.

Q: How do you define a variable in a class?

A: We define variables using ‘let’ keyword.

let decimal: number = 6;

Q: How do you define the data type of a variable?

A: Variable name is followed by data type. Variable name and data type are separated by a colon (:) character.

Syntax: let variable-name: data-type

let decimal: number = 6;

Q: Which are different data types in Angular?

A: Angular has a string, decimal, boolean, array data type.

let name: string = ‘Ram’;


let flag: boolean = True;
let salary: number = 100.10;
let code: number = 99;

Q: Can you define constants in Angular?

A: Yes, with the help of a const keyword.

const PI = 3.14;

Q: How do you define a constructer?

A: We define constructor using constructor keyword

Q: How many constructors can you define in a class?

A: Only one constructor can be defined in a class.


Q: How do you inherit a class?

A: We inherit class using the ‘extend’ keyword.

Q: How do you override a method?

A: Child class can override the parent class method.

Q: How do you overload a method?

A: You can define a function with optional parameters to achieve method overriding.

function paramTest(rollNo:number,name?:string) {
[Link](rollNo);
[Link](name);
}

Q: What is the difference between let and var keywords?


A: Keyword var provides methods-level access to a variable whereas let keyword provides block-level access to a variable.

React Routers and navigations


Q: How can you install React routing library?
A: Routing library can be installed by the following command:

npm install -g react-router-dom

Q: Why do you use routing?


A: Routing is used to develop a Single Page Application(SPA). It is sued to navigate from one page to another page in the SPA
application.

Q: What is SPA?
A: An SPA (Single-page application) is a web application that loads only a single web page in its lifetime, parts of the page are
updated dynamically. Dynamic parts are loaded using AJAX calls and page routing.

Q: What are the elements of Routing?


A: Elements of routing are:
React router provides four tags to manage the navigation in React application.
1. Router: Router is the top-level component. It encloses the entire application.
2. Link: It is an anchor tag. It creates hyperlinks to navigate to the target URL
3. Routes and Route: Both are used together. Route maps a target URL to the component. Routes contain multiple Route tags.
The Routes tag displays a route component based on the navigation URL.

For example

<Router>
<div>
<Link to = "/welcome" > Welcome</Link>
<Link to = "/login" > Login </Link>
<Routes>
<Route exact path = "/" component = { Login }/>
<Route path = "/welcome" component = { Welcome }/>
<Route component = { NotFound }/>
</Routes>
<Footer name="Rays"/>
</div>
</Router>

Q: How can we navigate from one component to another?


A: Navigation is done by <Link></Link> tag

<Link to = "/welcome"> Welcome</Link>

Installation and Configuration


Q: How can you install Angular CLI?

A: We install angular using “npm install @angular/cli ” command

npm install -g @angular/cli


npm install -g @angular/cli@8.1.2

Q: What is CLI?

A: Angular CLI stands for Angular “Command Line Interface”. CLI is used to generate angular components, projects, and run the
project.

Q: What is NPM?

A: It is the Node Package Manager. It is an online repository for open-source [Link] packages. CLI is installed using NPM.

Q: What is the latest version of Angular ?

Observable Vs Promise Object


Q: What are the differences between Observable and Promise objects?

1. Observable can handle multiple responses for a request whereas Promise can handle only single response for a request.

2. HTTP Request initiated by Observable object can be canceled whereas HTTP request initiated by Promise cannot be
canceled.

Q: How do you get Promise object in Angular 8?

A: We can get a Promise object using toPromise() method

constructor(private http: HttpClient) { }


private search(term) {
[Link](url).toPromise().then((data) => { .. });
}
Q: How do you use a promise object?
A: Sorry, I never get a chance to use it
. If I have to do it I can do it.

Component interaction
Component interaction can be done using @input decorator.

Data from one component (called parent component) can be passed to another component (child component).

Child components must define receiving parameters using @input decorator

Here Data Component is receiving two input elements thus child component

@Component({
selector: 'app-data',
template: '<li>Name is {{name}} and age is {{age}}</li>'
})
export class DataComponent implements OnInit {
@Input() name: string;
@Input() age: number;
}

Another component can use it using a selector name and passing two parameters using the following syntax:

<app-data [name]= “Ram” [age]=”16”></app-data>

Here is another component Two that uses Data component

import { Component, OnInit } from '@angular/core';


@Component({
selector: 'app-two',
template: `
<h2> Total person {{[Link]}} </h2>
<app-data *ngFor="let p of list" [name]= [Link] [age]=[Link]></app-data>
`
})
export class TwoComponent implements OnInit {
list = [
{"name": "jay", "age":16},
{"name": "Ajay", "age":18},
{"name": "Vijay", "age":20},
];
}

Q: What is the function of the @input decorator


A: It is used to pass attribute values to a component.

Q: What is the function of the @Output decorator


A: @Output decorator is used to raise an event

Login – User Story / Use case


Q: How do you create Login functionality in your application

A: For Login screen we will generate Login component. We will use command “ng g c Login” to generate Component.

Q: Which files are generated for Login component?

A:

1. It generates [Link] type-script file which contains control logics.


2. It generates [Link] html file which contains view logics.
3. It generates [Link] file
4. It generates [Link] file for unit test.
5. Component is automatically configured in application configuration file [Link].

Q: Can you write Login component manually?

A:

1. Yes, we can create Login component manually.


2. Login typescript and Login HTML page are created
3. Login route is defined in [Link] file.
4. Component configuration is done in application configuration file [Link] file.

Q: What code will you write in Login typescript?

A:

1. Type script will define LoginComponent class which implements OnInit interface.
2. We will define two attributes userId and password. These attributes will be bound with Login HTML form.
3. We will define signin() method which will do authentication of user with help of UserService.

export class LoginComponent


implements OnInit {
public userId:string = 'Enter User ID';
public password:string = '';
public message:string = 'No message';
constructor(router: Router, service:UserService) { }
ngOnInit() {}
signIn(){
if([Link]([Link],[Link])){
[Link]('/welcome');
}else{
[Link] = 'Invalid login id or password';
}
}

Q: What code will you write in Login HTML form?

A: We will create html Form and bind form input elements with userId and password typescript variables.

We will bind on-click event of Sign-In button with method signin() method.

<p style="color:red" >{{message}}</p>


<form >
User ID: <input [(ngModel)]="userId" name="userId" type="text">
Password: <input [(ngModel)]="password" name="password" type="password">
<button (click)="signIn()">Sign In</button>
</form>

Q: On successful login how will you navigate to Welcome page?

A: We will navigate using [Link]('/welcome') method.

Q: How do you do two-way data binding of userId and password variables?

A: We do two-way data binding using ng-model directive and square bracket and parenthesis.

User ID: <input [(ngModel)]="userId" >

Q: On unsuccessful login how do you display error message?

A: We set error message to controller attribute “message” and display it at html page using {{message}}.

Form Module
TODO

CORS
TODO
Component Lifecycle
What are Angular lifecycle hooks?

Angular provides a set of lifecycle hooks that allow you to tap into different stages of a component's lifecycle. These hooks are
methods that you can implement in your Angular component classes to perform specific tasks at particular moments. Here are the
commonly used Angular lifecycle hooks:

1. ngOnChanges: This hook is called whenever an input property of the component changes.
2. ngOnInit: This hook is called once after the component has been initialized and its input properties have been set.
3. ngDoCheck: This hook is called during every change detection cycle. It allows you to implement custom change
detection logic.
4. ngAfterContentInit: This hook is called after the component's content has been projected into its view.
5. ngAfterContentChecked: This hook is called after the component's projected content has been checked.
6. ngAfterViewInit: This hook is called after the component's view has been initialized.
7. ngAfterViewChecked: This hook is called after the component's view has been checked.
8. ngOnDestroy: This hook is called just before the component is destroyed. It is used for cleanup tasks and unsubscribing
from observables.

By implementing these hooks, you can perform tasks like initialization, cleanup, responding to input changes, and interacting with
the component's view at different stages of its lifecycle.

Example code
export class PeekABooDirective implements OnInit {
export class SpyDirective implements OnInit, OnDestroy {
export class AfterViewComponent implements AfterViewChecked, AfterViewInit {
export class AfterContentComponent implements AfterContentChecked, AfterContentInit {

You might also like