Angular Interview Quetion s
Angular Interview Quetion s
AngularJS Angular
This uses use JavaScript to build the application Introduced the typescript to write the applicatio
Difficulty in SEO friendly application development Ease to create SEO friendly applications
3. What is TypeScript?
TypeScript is a typed superset of JavaScript created by Microsoft that adds optional
types, classes, async/await, and many other features, and compiles to plain
JavaScript. Angular built entirely in TypeScript and used as a primary language. You
can install it globally as
document.body.innerHTML = greeter(user);
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{title}}</h1>
<div>Learn Angular6 with examples</div>
</div> `,
})
Component Directive
Component is used to break up the application into Directive is use to design re-usable
smaller components components
@Component ({
selector: 'my-app',
template: '
<div>
<h1>{{title}}</h1>
<div>Learn Angular</div>
</div>
'
})
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
i. ngOnChanges: When the value of a data bound property changes, then this
method is called.
ii. ngOnInit: This is called whenever the initialization of the directive/component
after Angular first displays the data-bound properties happens.
iii. ngDoCheck: This is for the detection and to act on changes that Angular
can't or won't detect on its own.
iv. ngAfterContentInit: This is called in response after Angular projects
external content into the component's view.
v. ngAfterContentChecked: This is called in response after Angular checks the
content projected into the component.
vi. ngAfterViewInit: This is called in response after Angular initializes the
component's views and child views.
vii. ngAfterViewChecked: This is called in response after Angular checks the
component's views and child views.
viii. ngOnDestroy: This is the cleanup phase just before Angular destroys the
directive/component.
<button (click)="logout()"></button>
@Component({
selector: 'my-component',
template: '<div>Class decorator</div>',
})
export class MyComponent {
constructor() {
console.log('Hey I am a component!');
}
}
@NgModule({
imports: [],
declarations: [],
})
export class MyModule {
constructor() {
console.log('Hey I am a module!');
}
}
ii. Property decorators Used for properties inside classes, e.g. @Input and
@Output
iii. Method decorators Used for methods inside classes, e.g. @HostListener
@Component({
selector: 'my-component',
template: '<div>Method decorator</div>'
})
export class MyComponent {
@HostListener('click', ['$event'])
onHostClick(event: Event) {
// clicked, `event` available
}
}
iv. Parameter decorators Used for parameters inside class constructors, e.g.
@Inject
@Component({
selector: 'my-component',
template: '<div>Parameter decorator</div>'
})
export class MyComponent {
constructor(@Inject(MyService) myService) {
console.log(myService); // MyService
}
}
Below are the list of few commands, which will come handy while creating angular
projects
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
3. What is a service?
A service is used when a common functionality needs to be provided to various
modules. Services allow for greater separation of concerns for your application and
better modularity by allowing you to extract common functionality out of
components. Let's create a repoService which can be used across components,
fetchAll(){
return this.http.get('https://api.github.com/repositories');
}
}
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}
<p *ngIf="user.age > 18">You are not eligible for student pass!</p>
Note: Angular isn't showing and hiding the message. It is adding and removing the
paragraph element from the DOM. That improves performance, especially in the
larger projects with many data bindings.
<h3>
{{title}}
<img src="{{url}}" style="height:30px">
</h3>
In the example above, Angular evaluates the title and url properties and fills in the
blanks, first displaying a bold application title and then a URL.
iii. new
iv. increment and decrement operators, ++ and --
v. operator assignment, such as += and -=
vi. the bitwise operators | and &
vii. the template expression operators
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18); // June 18, 1987
}
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'dd/mm/yyyy'}}</p>` // 18/06/1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
Note: The parameter value can be any valid template expression, such as a string
literal or a component property.
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'fullDate' | uppercase}}
</p>` // THURSDAY, JUNE 18, 1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
@Pipe({name: 'myCustomPipe'})
ii. The pipe class implements the PipeTransform interface's transform method
that accepts an input value followed by optional parameters and returns the
transformed value. The structure of pipeTransform would be as below,
interface PipeTransform {
transform(value: any, ...args: any[]): any
}
iii. The @Pipe decorator allows you to define the pipe name that you'll use within
template expressions. It must be a valid JavaScript identifier.
@Pipe({name: 'customFileSizePipe'})
export class FileSizePipe implements PipeTransform {
transform(size: number, extension: string = 'MB'): string {
return (size / (1024 * 1024)).toFixed(2) + extension;
}
}
Now you can use the above pipe in template expression as below,
template: `
<h2>Find the size of a file</h2>
<p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
`
/* JavaScript imports */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@Injectable()
export class UserProfileService {
constructor(private http: HttpClient) { }
getUserProfile() {
return this.http.get(this.userProfileUrl);
}
}
iii. Create a component for subscribing service: Let's create a component called
UserProfileComponent(userprofile.component.ts) which inject
UserProfileService and invokes the service method,
fetchUserProfile() {
this.userProfileService.getUserProfile()
.subscribe((data: User) => this.user = {
id: data['userId'],
name: data['firstName'],
city: data['city']
});
}
Since the above service method returns an Observable which needs to be subscribed
in the component.
getUserResponse(): Observable<HttpResponse<User>> {
return this.http.get<User>(
this.userUrl, { observe: 'response' });
}
fetchUser() {
this.userService.getProfile()
.subscribe(
(data: User) => this.userProfile = { ...data }, // success path
error => this.error = error // error path
);
}
It is always a good idea to give the user some meaningful feedback instead of
displaying the raw error object returned from HttpClient.
// Execute with the observer object and Prints out each item
myObservable.subscribe(myObserver);
// => Observer got a next value: 1
// => Observer got a next value: 2
// => Observer got a next value: 3
// => Observer got a next value: 4
// => Observer got a next value: 5
// => Observer got a complete notification
interface Observer<T> {
closed?: boolean;
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}
myObservable.subscribe(myObserver);
Note: If you don't supply a handler for a notification type, the observer ignores
notifications of that type.
Observable Promise
Declarative: Computation does not start until subscription so that they can Execute immediately on
be run whenever you need the result creation
Subscribe method is used for error handling which makes centralized and Push errors to the child
predictable error handling promises
Provides chaining and subscription to handle complex applications Uses only .then() clause
myObservable.subscribe({
next(num) { console.log('Next num: ' + num)},
error(err) { console.log('Received an errror: ' + err)}
});
myObservable.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
After applying types typescript validates input value and their types,
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
ii. Apply the attribute directive as an attribute to the host element(for example,
ng serve
<base href="/">
<router-outlet></router-outlet>
<!-- Routed components go here -->
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" routerLinkActive="active">List of todos</a>
<a routerLink="/completed" routerLinkActive="active">Completed todos</a>
</nav>
<router-outlet></router-outlet>
i. NavigationStart,
ii. RouteConfigLoadStart,
iii. RouteConfigLoadEnd,
iv. RoutesRecognized,
v. GuardsCheckStart,
vi. ChildActivationStart,
vii. ActivationStart,
viii. GuardsCheckEnd,
ix. ResolveStart,
x. ResolveEnd,
xi. ActivationEnd
xii. ChildActivationEnd
xiii. NavigationEnd,
xiv. NavigationCancel,
xv. NavigationError
xvi. Scroll
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
i. Just-in-Time (JIT)
ii. Ahead-of-Time (AOT)
ng build
ng serve
Note: The ng build command with the --prod meta-flag (ng build --prod) compiles
with AOT by default.
@Component({
providers: [{
provide: MyService, useFactory: () => getService()
}]
})
function getService(){
return new MyService();
}
@Component({
providers: [{
provide: MyService, useFactory: getService
}]
})
If you still use arrow function, it generates an error node in place of the function.
When the compiler later interprets this node, it reports an error to turn the arrow
function into an exported function. Note: From Angular5 onwards, the compiler
automatically performs this rewriting while emitting the .js file.
@Component({
selector: 'app-root'
})
Remember that the compiler can’t fold everything. For example, spread operator on
arrays, objects created using new keywords and function calls.
@NgModule({
declarations: [TypicalComponent]
})
export class TypicalModule {}
xv. Function calls are not supported: The compiler does not currently support
function expressions or lambda functions. For example, you cannot set a
provider's useFactory to an anonymous function or arrow function as below.
xvi. providers: [
xvii. { provide: MyStrategy, useFactory: function() { ... } },
xviii. { provide: OtherStrategy, useFactory: () => { ... } }
]
xix. Destructured variable or constant not supported: The compiler does not
support references to variables assigned by destructuring. For example, you
cannot write something like this:
xx. import { user } from './user';
xxi.
xxii. // destructured assignment to name and age
xxiii. const {name, age} = user;
xxiv. ... //metadata
xxv. providers: [
xxvi. {provide: Name, useValue: name},
xxvii. {provide: Age, useValue: age},
]
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
{
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
@Component({
selector: 'my-component',
template: '{{user.contacts.email}}'
})
class MyComponent {
user?: User;
}
template: '{{$any(user).contacts.email}}'
The $any() cast function also works with this to allow access to undeclared members
of the component.
template: '{{$any(this).contacts.email}}'
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.name}} contacted through {{contact!.email}}
</span>'
})
class MyComponent {
user?: User;
contact?: Contact;
setData(user: User, contact: Contact) {
this.user = user;
this.contact = contact;
}
}
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.contact.email}} </span>'
})
class MyComponent {
user?: User;
}
i. Angular packages: Angular core and optional modules; their package names
begin @angular/.
ii. Support packages: Third-party libraries that must be present for Angular
apps to run.
iii. Polyfill packages: Polyfills plug gaps in a browser's JavaScript
implementation.
ng new codelyzer
ng lint
101. What is angular animation?
Angular's animation system is built on CSS functionality in order to animate any
property that the browser considers animatable. These properties includes positions,
sizes, transforms, colors, borders etc. The Angular modules for animations
are @angular/animations and @angular/platform-browser and these
dependencies are automatically added to your project when you create a project
using Angular CLI.
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule
],
declarations: [ ],
bootstrap: [ ]
})
export class AppModule { }
import {
trigger,
state,
style,
animate,
transition,
// ...
} from '@angular/animations';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
animations: [
// animation triggers go here
]
})
103. What is State function?
Angular's state() function is used to define different states to call at the end of each
transition. This function takes two arguments: a unique name like open or closed and
a style() function. For example, you can write a open state function
state('open', style({
height: '300px',
opacity: 0.5,
backgroundColor: 'blue'
})),
state('close', style({
height: '100px',
opacity: 0.8,
backgroundColor: 'green'
})),
@Component({
selector: 'app-animate',
templateUrl: `<div [@changeState]="currentState" class="myblock mx-auto"></div>`,
styleUrls: `.myblock {
background-color: green;
width: 300px;
height: 250px;
border-radius: 5px;
margin: 5rem;
}`,
animations: [
trigger('changeState', [
state('state1', style({
backgroundColor: 'green',
transform: 'scale(1)'
})),
state('state2', style({
backgroundColor: 'red',
transform: 'scale(1.5)'
})),
transition('*=>state1', animate('300ms')),
transition('*=>state2', animate('2000ms'))
])
]
})
export class AnimateComponent implements OnInit {
@Input() currentState;
constructor() { }
ngOnInit() {
}
}
i. You can enable ivy in a new project by using the --enable-ivy flag with the ng
new command
{
"compilerOptions": { ... },
"angularCompilerOptions": {
"enableIvy": true
}
}
{
"projects": {
"my-project": {
"architect": {
"build": {
"options": {
...
"aot": true,
}
}
}
}
}
}
After that add the following to the "compilerOptions" section of your project's
tsconfig.json
"plugins": [
{"name": "@angular/language-service"}
]
Note: The completion and diagnostic services works for .ts files only. You need to
use custom plugins for supporting HTML files.
iii. The component app.component.ts file updated with web worker file
Note: You may need to refactor your initial scaffolding web worker code for sending
messages to and from.
i. @Component()
ii. @Directive()
iii. @Pipe()
iv. @Injectable()
v. @NgModule()
@Input() myProperty;
@Output() myEvent = new EventEmitter();
A Subject is like an Observable, but can multicast to many Observers. Subjects are
like EventEmitters: they maintain a registry of many listeners.
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
subject.next(2);
i. It creates the possibility of building your back-ends and front-ends with the
same tool
ii. The incremental build and tests
iii. It creates the possibility to have remote builds and cache on a build farm.
ng add @angular/bazel
ii. Use in a new application: Install the package and create the application
with collection option
When you use ng build and ng serve commands, Bazel is used behind the scenes and
outputs the results in dist/bin folder.
bazel build [targets] // Compile the default output artifacts of the given targets.
bazel test [targets] // Run the tests with *_test targets found in the pattern.
bazel run [target]: Compile the program represented by target and then run it.
and define view child directive and access it in ngAfterViewInit lifecycle hook
@ViewChild('uname') input;
ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
(or)
let headers = new HttpHeaders().set('header1', headerValue1); // create header
object
headers = headers.append('header2', headerValue2); // add a new header, creating a
new object
headers = headers.append('header3', headerValue3); // add another header
i. The first build contains ES2015 syntax which takes the advantage of built-in
support in modern browsers, ships less polyfills, and results in a smaller
bundle size.
ii. The second build contains old ES5 syntax to support older browsers with all
necessary polyfills. But this results in a larger bundle size.
Note: This strategy is used to support multiple browsers but it only load the code
that the browser needs.
This problem is resolved by using dynamic imports and IDEs are able to find it during
compile time itself.
buildTarget.options.optimization = true;
addBuildTargetOption();
It supports the most recent two versions of all major browsers. The latest version of
Angular material is 8.1.1
@NgModule({
imports: [
// Other NgModule imports...
LocationUpgradeModule.config()
]
})
export class AppModule {}
Note: A chrome browser also opens and displays the test output in the "Jasmine
HTML Reporter".
import 'web-animations-js';