Angular Interview Lyst9714
Angular Interview Lyst9714
1. What is Angular ?
3. What is typescript ?
In static type language like TypeScript programmer needs to specify data type of
variable during writing code whereas in dynamic typing language like javascript
there is no need to specify data type .
e.g. calculateSquare(no:number):number
{
return no*no;
}
If method return type is void means this method will NOT return any value .
It just perform some operation but do not return any value .
6. Tell me different data types present in TypeScript ?
like javascript , we can ' ' , " " both for string values
x="angular";
6. void type :- If method return type is void means this method will NOT return any
value . It just perform some operation but do not return any value .
Install node.js
Install Angular CLI
Angular CLI is a command-line interface tool which we use to create , run angular
app
Run the CLI command ng new and provide the name my-app, as shown here:
ng new my-app
The ng new command prompts you for information about features to include in the
initial app. Accept the defaults by pressing the Enter or Return key.
The Angular CLI installs the necessary Angular npm packages and other dependencies.
This can take a few minutes.
The CLI creates a new workspace and a simple Welcome app, ready to run.
Running Application
The Angular CLI includes a server, so that you can easily build and serve your app
locally.
Launch the server by using the CLI command ng serve, with the --open option.
ng serve –open
The --open (or just -o) option automatically opens your browser to
http://localhost:4200/.
The ng serve command launches the server, watches your files, and rebuilds the app
as you make changes to those files.
9. What are 4 building blocks of Angualr ?
Components
Services
Pipes
Directives
1. Components
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
2.Services
@Injectable({
providedIn: 'root'
})
export class HttpClientService
{
// some business logic methods
}
Service class contains some business logic methods which are called by different
component classes from our angular App .
3) Pipes
{{ ”hello” | uppercase }}
Angular has a lot of predefined pipes which are used to format the data .
4) Directives
e.g.
}
}
class Employee
{ constructor(eno : number , salary : number)
{
}
}
class Account
{
constructor(accno : number , balance : number) { }
class Account
{
constructor(accno : number , balance : number) { }
e.g. Mechanical Engineers draws diagram of car on paper . That diagram can be
considered as a class . When cars are actually manufactured then those cars are
called objects .
In order to call variables and functions from a class we must create object .
Here Account(1 , 1000) will call constructor from Account class and this
constructor will initialize variables accno and balance to 1 and 1000
respectively .
Now to access variables and methods/functions from an object we must define object
name .
Now , we can use this object name to access variables and functions from an
object .
Here to access variables rno and marks from an object we use object name .
e.g. alert(myObj.rno) will display value of rno .
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
@Component Decorator accepts one JavaScript object having key and value
pairs .Here we specify 3 things
styleUrls :- It specify CSS files which are used to style html file associated with
this component .
Using template , we can write HTML content in Type Script File itself instead of
writing it separately in HTML file .
When we write HTML content in separate file , we specify that file name using
templateUrl .
It will create a new folder Student and inside that 4 files will be present .
1. student.component.html
2. student.component.css
3. student.component.ts
4. student.component.spec.ts
<app-student></app-student>
<app-student></app-student>
<app-add-student></app-add-student>
Now we are running 2 component’s html files , first Student Compoent and second
AddStudentCompoent .
1) index.html
<body>
<app-root></app-root>
</body>
bootstrap: [AppComponent]
1) index.html
<body>
<app-student></app-student>
</body>
bootstrap: [StudentComponent]
When we bind value of variable from component class to HTML element (View
Template ) , we call it one way data binding .
String Interpolation
Property Binding
e.g. String variable msg ‘s value hello will be displayed in the input box .
In app.component.html file :-
<input value='{{msg}}'>
In app.component.ts file :-
e.g. HTML input element’s value property is bound with value of msg variable from
component class .
In app.component.html file :-
In app.component.ts file :-
With attribute binding we can set the value of an attribute directly. Angular team
recommends to use Property binding when possible and use attribute binding only
when there is no corresponding element property to bind.
<th [attr.colspan]="columnSpan">
<th attr.colspan="{{columnSpan}}">
class EmployeeComponent {
columnSpan: number = 2;
}
In two way data binding , component class variable value is applied to HTML
element and When HTML element value changes , it’s new value is applied to variable
from componet class . Hence it is 2 way data binding .
e.g.
<input [(ngModel)]=‘firstName'>
Here firstName is the variable from componet class . Value of this variable will be
displayed in the input box and when we change input box value , value of variable
firstName will also be chaged automatically .
For us to be able to use ngModel directive in our root module - AppModule, we will
have to import FormsModule first.
Here are the steps to import FormsModule into our AppModule
we define event handler function in typescript file (.ts file ) . Hence we need to
bind events which occur on HTML View template to function from component class ,
so that when event occurs this event handler will execute to handle the event .
Syntax :-
@Component({
selector: 'my-app',
template: `<button (click)='onClick()' >Click me</button>`
})
Every time we click the button, 'Button Clicked' message is logged to the console.
You can see this message under the Console tab
Whenever we select any option from select element , onchange event occurs
In app.component.html file :-
In app.compoent.ts file :-
display()
{
alert(this.selectedLanguage);
}
}
display() will execute whenever we select any option from select element .
Directive is a special feature added by Angular which makes HTML element more
dynamic .
@Component (
{
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
}
Structural Directive is used to change the structure of a HTML page . e.g. using
ngIf directive we can hide or show some html element , using ngFor directive we can
add new rows in a html table .
ngIf Directive :-
@Component({
selector: 'app-ng-if-simple',
template: `
<div *ngIf="show"> Angular is Fun </div>
`
})
As show variable value is false , therefore HTML <div> element will not be
displayed on browser .
ngFor Directive :-
employees: any[] = [
{
code: 'emp101', name: 'Tom‘
}
,
{
code: 'emp102', name: 'Alex'
} ];
Attribute Directive
The attribute directive changes the appearance or behavior of a DOM element. These
directives look like regular HTML attributes in templates.
NgStyle: Based on the component state, dynamic styles can be set by using NgStyle.
Many inline styles can be set simultaneously by binding to NgStyle.
ngSwitch Example :-
In app.component.html file :-
<ul [ngSwitch]="person">
</ul>
In app.component.ts
class AppComponent {
person : string = ‘Mohan’
}
Output :-
. Hello Mohan
ngStyle Example :-
e.g. Suppose we want display persons from different country with different color ,
then it is possible with ngStyle directive .
people: any[] = [
{
"name": "Peter Mark",
"country": 'UK'
},
{
"name": "John Mill",
"country": 'USA'
},
{
"name": "Rohan Jadhav",
"country": 'India'
},
];
getColor(country) {
switch (country) {
case 'UK':
return 'green';
case 'USA':
return 'blue';
case 'India':
return 'red';
}
}
In app.component.html :-
interface MyInterface
{
show(); // show() is just declared & not defined
}
All methods from interface are public by default . We should write a class which
defines undefined methods from the interface . Such class is called as
Implementation class of interface .
We can not create object of interface . But we can create object of implementation
class .
class InterfaceExComponent
{
obj: MyClass = new MyClass();
dispay()
{
this.obj.show();
}
}
e.g. Filling the array from component class with the contents from Database
ngOnInit()
{
this.obj.show();
}
}
Syntax :-
Data | Pipe
e.g.
A pipe can accept any number of optional parameters to fine-tune its output.
To add parameters to a pipe, follow the pipe name with a colon ( : ) and then the
parameter value (such as currency:'EUR').
If the pipe accepts multiple parameters, separate the values with colons .
e.g. To display date in a specific format , we can sepcify that format like below
{{ Unique | slice : 1 : 4 }} will render niq . Here slice pipe has accepted 2
values which are separated by :
Angular 2 also has the facility to create custom pipes. The general way to define a
custom pipe is as follows.
transform(parameters): returntype { }
}
Where,
A service in Angular is generally used when you need to reuse variable or method
across multiple components.
e.g. in service class , we will define a method which will fetch the all
employee records from a database . Then we use this method in any component class
.
e.g.
@Injectable({
providedIn: 'root'
})
export class DisplayService
{
sum(a,b)
{
return a+b;
}
}
Here , we have defined a service class DisplayService and we have defined one
method sum(a,b) into it . Now this sum(a,b) can be called by any component class
.
providedIn: 'root‘ indicates that this Service class is available to all component
classes from root module AppModule .
We know to call a method from a class , we need object of that class . Generally
we create object ourselves but in Service class case , it is recommended not to
create object programmatically ( explicitly ) .
Instead we should just declare the object . Object will be created by Angular and
it will be injected into our Component class automatically . This is know as
Dependency injection .
Hence such singleton service class object can be used to share some data across all
component classes .
e.g. If we want background color of all textboxes in all component classes should
be black , then in service class , we can define a variable colorChoice and
initialize it with value black . Then we will use this variable value in all
component classes to set background color of input .
@Component({
selector: 'app-employee’})
class EmployeeComponent
{
@Input
employeeName : string ;
}
In app.componnet.html file :-
<app-employee [employeeName] = “David” > </app-employee>
@Component({
selector: 'app-root',
template : `
eventHandler(data: any)
{
console.log(data); /* will print 10 on console */
}
}
Here When we click on button , it will call generate() which will raise
customEvent . This customEvent will sends value 10 to parent component .
Handling user input with forms is the cornerstone of many common applications.
Applications use forms to enable users to log in, to update a profile, to enter
sensitive information, and to perform many other data-entry tasks.
Angular provides two different approaches to handling user input through forms
Reactive forms
template-driven forms
Template-driven forms are very much similar to basic HTML forms . Here We use
[( ngModel )] directive for two way data binding .Most of the form related code
is written in HTML template itself , hence it is called as template driven forms .
e.g.
<form>
<input [(ngModel)]="first"><br><br>
<input [(ngModel)]="second"><br><br>
<input [(ngModel)]="result"><br><br>
<button (click)="calculateSum()">Sum</button><br><br>
</form>
class AddNumbersComponent
{
first : string ="10";
second: string ="20";
result : number;
calculateSum()
{
}
}
Values of first , second and result variable will be displayed on textboxes from
html template form . To use [(ngModel )] directive we must add FormsModule in
imports array of ngModule directive in app.module.ts file .
Forms typically contain several related controls. Reactive forms provide way of
grouping multiple related controls into a single input form.
Creating form control instances manually can become repetitive when dealing with
multiple forms.
Modules are a great way to organize an application and extend it with capabilities
from external libraries.
Angular libraries are NgModules, such as FormsModule, HttpClientModule,
and RouterModule.
NgModules groups related components, directives, pipes , Services into one block
.
Every Angular app has at least one module, the root module. You bootstrap that
module to launch the application.
The root module is all you need in a simple application with a few components.
As the app grows, you refactor the root module into feature modules that represent
collections of related functionality. You then import these modules into the root
module.
The Angular CLI generates the following basic AppModule when creating a new app.
// imports
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
@NgModule takes a metadata object that tells Angular how to compile and launch the
application.
The default application created by the Angular CLI only has one
component, AppComponent, so it is in both the declarations and
the bootstrap arrays.
You must declare every component in exactly one NgModule class. If you use a
component without declaring it, Angular returns an error message.
These declared classes are visible within the module but invisible to components in
a different module unless they are exported from this module and the other module
imports this one.
As your app grows, you can organize code relevant for a specific feature. This
helps apply clear boundaries for features. With feature modules, you can keep code
related to a specific functionality or feature separate from other code.
Assuming you already have an app that you created with the Angular CLI, create a
feature module using the CLI by entering the following command in the root project
directory. You can omit the "Module" suffix from the name because the CLI appends
it:
This causes the CLI to create a folder called my with a file inside
called my.module.ts with the following contents:
@NgModule({
imports: [
CommonModule
],
declarations: []
})
export class MyModule { }
This generates a folder for the new component within the my folder and updates the
feature module with the FirstComponent info .
@NgModule({
imports: [
CommonModule
],
declarations: [
FirstComponent
],
})
To import feature module my into the AppModule, add it to the imports array:
@NgModule({
declarations: [
AppComponent
],
imports: [
MyModule // add the feature module here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Add below line in my.module.ts file , just beneath the declarations array
exports: [
FirstComponent
]
Next, in the AppComponent, app.component.html, add the tag <app-first> , selector
of FirstComponent .
With single-page apps, your users stay on a single page, but their view of that
page changes depending on what the user wants to do.
To handle the navigation from one view to the next, you use the Angular router. The
router enables navigation by interpreting a browser URL as an instruction to change
the view.
These paths will be used to execute html files associated with these
components .
<nav>
<a routerLink = "/home">Home</a>
<a routerLink = "/aboutus">About Us </a>
</nav>
<router-outlet></router-outlet>
<router-outlet> tag indicate the location where Html Pages related to routing
will be displayed . e.g. If we click on Home link , then home.component.html
file will be displayed in the place where <router-outlet> tag is written .
Router class contains navigate() method which can be used for routing .
class AppComponent {
goHome()
{
this.myRoute.navigate(["/home"]);
}
HttpClient class
Most front-end applications need to communicate with a server over the HTTP
protocol, in order to download or upload data and accesss other back-end services.
Angular provides a simplified client HTTP API for Angular applications,
the HttpClient service class in @angular/common/http.
Use the HTTPClient.get() method to fetch data from a server. The aynchronous method
sends an HTTP request and fetches the data from a server .
imports : [ HttpClientModule ]
getStudents()
{
return this.httpClient.get<Student[]>('http://localhost:8085/students');
}
class HttpClientService
{
public viewStudent(rno)
{
return this.httpClient.get<Student>("http://localhost:8085/students" + "/"+ rno
);
}
Here requested URL will return JSON String having details of that student
object whose roll no is passed here . This JSON String will be converted into
Student object automatically by Angular .
class HttpClientService
{
public createStudent(student) {
}
Here , we are sending Student object to server . Server may save details of this
student object in a database .
class HttpClientService
{
public updateStudent(student)
{
Here , we are sending Student object to server . Server will update the details of
this student object in a database .
class HttpClientService
{
public deleteStudent(student)
{
return this.httpClient.delete("http://localhost:8085/students" + "/"+ stude
nt.rno);
}
Here , we are sending roll number of that Student object which we want to delete
to server . Server will delete the details of this student object in a database .
class AddstudentComponent {
createStudent(): void
{
this.httpClientService.createStudent(this.student)
.subscribe( data => {
alert("Student created successfully.");
});
};
updateStudent(): void {
this.httpClientService.updateStudent(this.student)
.subscribe( data => {
alert("Student updated successfully.");
});
};
viewStudent(): void {
this.httpClientService.viewStudent(this.student.rno)
.subscribe( response => {
this.student=response;
});
};
deleteStudent() :void
{
this.httpClientService.deleteStudent(this.student)
.subscribe( data => {
alert("Student Deleted successfully.");
});
With web storage, web applications can store data locally within the user's
browser.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is
never transferred to the server.
Web storage is per origin (per domain and protocol). All pages, from one origin,
can store and access the same data.
HTML web storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the browser
tab is closed)
sessionStorage.setItem("userName", “ramesh”);
localStorage.setItem("userName", “ramesh”);
tsc command is used to compile type script file . After compilation , typescript
file will be converted into javascript file . Then this javascript file is
executed using node command