Prev Next

Angular / Angular basics

1. What is AngularJS? 2. What are the key features of AngularJS. 3. What are the advantages of using AngularJS? 4. What are the key components of AngularJS Framework? 5. What are the limitations of using AngularJS? 6. Explain about AngularJS Expression. 7. Can we pass parameters to an AngularJS controller? 8. What is bower? 9. What is a component in Angular? 10. What are .ts extension files? 11. How do you communicate between different modules of your application using angularjs? 12. How does interpolation, for example "{{ someModel }}" works? 13. What is $rootScope and how does it relate to $scope? 14. Advantages of components in AngularJS. 15. What is ngBind directive in AngularJS? 16. What is ngIf directive in AngularJS? 17. Difference between ng-show/ng-hide directives and ngIf in angularjs. 18. Explain directives in angularJS. 19. What is the role of selector property of components in AngularJS? 20. Explain Angular 2 architecture. 21. Type of module in Angular 2. 22. Explain root module in angular2. 23. What is an Angular module? 24. What does the npm start do? 25. How do I create a multiline template in the Angular component? 26. What is RXJS and how does it relate to Angular? 27. How to check if a variable is defined using ngIf in Angular? 28. How to check for multiple conditions using Angular ng-if? 29. Features of Angular2. 30. Explain ng-container in Angular. 31. Types of directives in Angular. 32. Difference between Directive and component in Angular. 33. Difference between ngOnInit and ngAfterViewInit of Angular2. 34. Difference between Constructor and ngOnInit in Angular. 35. What is a zone in Angular? 36. Can we use ngIf and ngFor on the same element in Angular? 37. What is router-link directive? 38. Difference between router-link and [router-link] with brackets. 39. Explain Hot Module Replacement (HMR). 40. What is webpack? 41. Difference between ng model and ng bind directives. 42. What is forRoot and forChild method in angular? 43. How do you create and register/provide service using ng CLI? 44. Difference between declarations, providers, and import in NgModule. 45. Explain pipes in Angular. 46. What is angular routing? 47. How to check the Angular version installed? 48. Explain the structure of Angular application projects. 49. What is angular CLI? 50. Elements of the Component decorator in Angular. 51. Explain Angular services. 52. How do I create a service as a singleton in Angular? 53. What is service worker and its advantages in Angular? 54. How does *ngIf directive works? 55. Difference between ng-class and ng-style directives. 56. Difference between Component and template/templateURL. 57. Default view encapsulation model in Angular. 58. Types of directives in Angular. 59. What are structural directives in Angular? 60. Difference between Structural and attribute directives. 61. What is <ng-template> in Angular? 62. Explain <ng-container> element in Angular. 63. Name a few builtin pipes in Angular that you are aware of. 64. What are the different types of Pipes in Angular? 65. What is JsonPipe? 66. What are the methods in Angular FormBuilder? 67. What is ngForm directive? 68. What are the child classes of AbstractControl? 69. Difference between Promises and Observable. 70. What is NGModule? 71. Can a Angular component be declared in multiple modules? 72. Design a game using Angular in which the user should click on the highlighted area to score before it vanishes. Also, it should display score with different levels like easy/medium/difficult. 73. What is tree shaking in Angular? 74. What defines an Angular view? 75. Difference between a view, a host view, and an embedded view. 76. Difference between createEmbeddedView and createComponent in Angular. 77. Various forms of data binding markup in Angular. 78. Is ngModel an attribute directive? 79. Mention a few roles of Services in Angular. 80. How do I make a parent component listen for child events?
Could not find what you were looking for? send us the question and we would be happy to answer your question.

What is AngularJS?

AngularJS is a javascript framework used for creating single web page applications and dynamic web apps.

AngularJS is a structural framework that lets you use HTML as your template language and enables you extend HTML syntax to express your application components clearly and succinctly.

What are the key features of AngularJS.
  • Two Way Data-Binding,
  • Templates,
  • MVC,
  • Dependency Injection,
  • Directives,
  • Testing.
What are the advantages of using AngularJS?
  • AngularJS is a powerful JavaScript based framework that enables creating Single Page Application (SPA) and RICH Internet Application(RIA).
  • AngularJS applications are cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, free and used by many developers around the world. It is licensed under the Apache License version 2.0. https://www.madewithangular.com has the list of popular applications built with AngularJS.
  • AngularJS enables developers to write client side Javascript application using MVC (Model View Controller) pattern.

    Using AngularJS developers write less code and achieve more functionality.

  • AngularJS applications are unit testable.
  • AngularJS provides two-way data binding capability to HTML thus facilitating the users a rich and responsive experience.
  • AngularJS uses dependency injection and make use of separation of concerns. AngularJS helps creating reusable components.
What are the key components of AngularJS Framework?

The below 3 core directives forms the AngularJS framework.

  • ng-app − directive defines and links an AngularJS application to HTML.
  • ng-model − directive binds the AngularJS application data to HTML input controls.
  • ng-bind − binds the AngularJS Application data to HTML tags.
What are the limitations of using AngularJS?
  • AngularJS runs on the client side browser that make it quite obvious to compromise on the Application security. By minimizing the JS files in Production environment and leveraging other security measures, we could build better application security.
  • Client must enable JavaScript in the browser to run the AngularJS applications. Otherwise, the user will just see a blank page.
  • Memory leak in JavaScript can cause slow down of any browser. AngularJS works well only from Internet Explorer 8.0 onwards and doesn't support any older versions.
Explain about AngularJS Expression.

AngularJS expressions are code snippets that are usually placed in binding inside double braces such as {{ expression }}.

Expressions are used to bind application data to html. AngularJS expressions are pure javascript expressions and outputs the data where they are used.

Can we pass parameters to an AngularJS controller?

Yes. Using ng-init directive and a simple init function we can pass parameters to the AngularJS Controller.

What is bower?

Bower is a package manager for the web, Bower can manage AngularJS components that contain HTML, CSS, JavaScript, fonts or even image files.

Bower does not concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies.

What is a component in Angular?

Angular applications are made up of components. A component is the combination of an HTML template and a component class that controls a portion of the screen.

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

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'javapedia.net'; }

A component is a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure.

What are .ts extension files?

They are TypeScript files, a superset of JavaScript. Angular uses TypeScript because its types make it easy to support developer productivity with tooling.

How do you communicate between different modules of your application using angularjs?

The below are the ways to communicate between modules of your application using core AngularJS functionality include,

  • Using services,
  • Using events,
  • By assigning models on $rootScope,
  • Directly between controllers, using $parent, $$childHead, $$nextSibling.
  • Directly between controllers, using ControllerAs, or other forms of inheritance.
How does interpolation, for example "{{ someModel }}" works?

It relies on $interpolation, a service called by the compiler. It evaluates text and markup which may contain AngularJS expressions. For every interpolated expression, a watch() is set. $interpolation returns a function, which has a single argument, "context". By calling that function and providing a scope as context, the expressions are $parse()-ed against that scope.

What is $rootScope and how does it relate to $scope?

$rootScope is the parent object of all $scope objected created in an angular application.

Advantages of components in AngularJS.
  • Simpler configuration than plain directives.
  • Promote sane defaults and best practices.
  • Optimized for component-based architecture.
  • Writing component directives will make it easier to upgrade to Angular 2.

What is ngBind directive in AngularJS?

The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before AngularJS compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

What is ngIf directive in AngularJS?

ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively.

'then' template is the inline template of ngIf unless bound to a different value and 'else' template is blank unless it is bound.

Difference between ng-show/ng-hide directives and ngIf in angularjs.

ng-show/ng-hide will always insert the DOM element, but will display/hide it based on the condition. While ng-if will not insert the DOM element until the condition is not fulfilled.

Explain directives in angularJS.

AngularJS directives are used to extend HTML and DOM elements's behavior. These are the special attributes, that start with ng- prefix, instructs AngularJS HTML compiler ($compile) to attach a specified behavior to that DOM element.

Examples of AngularJS inbuilt directives include ngApp, ngInit, ngBind ,ngModel and ngClass.

What is the role of selector property of components in AngularJS?

The selector property instructs the Angular to display the component inside a custom tag in the index.html.

@Component({
  selector: 'myApp',
  template: `<h1>Hi {{name}}</h1>`
})

In the above example, selector tells the Angular to display component inside the custom tag 'myApp'.

<myApp>Load Component content here ...</myApp>

Explain Angular 2 architecture.

Angular 2 architecture consists of 8 modules,

  • Module,
  • Component,
  • Template,
  • Metadata,
  • Data binding,
  • Service,
  • Directive,
  • and Dependency Injection.
Type of module in Angular 2.

There are 2 types, Root and feature modules. There is only one root module and many feature modules in an Angular application.

Explain root module in angular2.

Root module is an angular module class that describes how the application is assembled and the parts fitted together. The root module is usually named as AppModule.

Every angular application has at least one module, the root module to bootstrap and launch the application. There is only one root module for an angular application.

What is an Angular module?

A module groups and work as container for the different parts of application such as controllers, services, directives, pipes and so on.

What does the npm start do?

npm start command usually run 2 commands parallelly. 1 command watches for typescript file changes to refresh and the other for lite-server to load the index html file on the browser and refresh as required.

How do I create a multiline template in the Angular component?

Use backtick "`" instead of single quote.

What is RXJS and how does it relate to Angular?

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code. Angular is built on top of RXJS.

How to check if a variable is defined using ngIf in Angular?

Check the variable against undefined keyword.

*ngIf= "dolRecords !== undefined" 

How to check for multiple conditions using Angular ng-if?

Use logical operator such as and (&&) to evaluate multiple conditions.

Features of Angular2.

Angular 2 is component based. Controllers and $scope are no longer in use and have been replaced by components and directives.

The specification for directives is considerably simplified and using @Directive annotation, a directive can be declared.

Improved dependency injection model in Angular2.

Use of TypeScript, a typed super set of JavaScript in Angular. The presence of types makes the code less prone to run-time errors.

TypeScript has generics and lambda feature.

With Angular 2 the Form Builder and Control Group are defined that makes it easy to build forms and it's validations .

Explain ng-container in Angular.

ng-container is a logical container used to group nodes but is not rendered in the DOM tree as a node.

ng-container can conditionally append a group of elements, using ngif in your application, it eliminates the need to wrap them with another element.

 <ng-container *ngIf="true">
        <h2>Title</h2>
      
 </ng-container>

Types of directives in Angular.

There are 3 types.

  • Component,
  • Attribute Directive,
  • and Structural.
Difference between Directive and component in Angular.

Directives associate behavior to elements in the DOM, consisting of Structural, Attribute and Component types.

Components are a type of directive in Angular that allows to utilize web component functionality - encapsulated, reusable elements available throughout our application.

Difference between ngOnInit and ngAfterViewInit of Angular2.

ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.

ngAfterViewInit is also a lifecycle hook that is called after a component's view has been fully initialized.

Difference between Constructor and ngOnInit in Angular.

The Constructor of the class is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better DI analyzes the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor.

ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.

What is a zone in Angular?

A Zone is an execution context that persists across async tasks and allows the creator of the zone to observe and control execution of the code within the zone.

These execution contexts allow Angular to track the start and completion of asynchronous activities and perform tasks as required (for example, change detection).

Can we use ngIf and ngFor on the same element in Angular?

No, Angular2 does not support more than one structural directive on the same element.

You may use the element that allows you to use separate elements for each structural directive in a nested format.

What is router-link directive?

The RouterOutlet directive tells our router where to render the content in the view.

Difference between router-link and [router-link] with brackets.

Use brackets to pass a bindable property (a variable).

Explain Hot Module Replacement (HMR).

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload. This can significantly speed up development process.

What is webpack?

webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into one or more bundles.

Difference between ng model and ng bind directives.

'ng-model' is an angular directive used for achieving two-way data binding. Any modifications to that model from the Scope/Controller will be automatically propagated to the view regardless of whether the view is asking for the updated data and any modifications to that model from the View will be immediately reflected back to the Scope/Controller.

'ng-bind' is an angular directive used for achieving one-way data binding. After the binding, any modifications to that model from the scope/controller will be automatically propagated to the view regardless of whether the view is asking for the updated data. No propagation happens for any change to the model from the view to the controller.

What is forRoot and forChild method in angular?

The forRoot is a static method and it helps to configure the modules. For example, RouterModule.forRoot.

The RouterModule also has forChild method, static method used to configure the routes of lazy-loaded modules. The forRoot and forChild are the traditional names for methods that configure services in root.

How do you create and register/provide service using ng CLI?

It is possible to provide the service when creating the service. When you create the service using NG CLI specify the module using (--module or -m) to provide as shown below.

ng g s KenoDataService --module=app.module

Difference between declarations, providers, and import in NgModule.

imports makes the exported declarations of other modules available in the current module.

declarations make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.

providers make services and values known to DI. They are added to the root scope and they are injected to other services or directives that have them as the dependency.

Explain pipes in Angular.

Angular pipes is a way to write display-value transformations that you can declare in your HTML.

A pipe takes in data as input and transforms it into the desired output. In the below example, pipe transforms a component's birthday property into a human-friendly date.

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

@Component({
  selector: 'app-birthday',
  template: `<p>The User's birthday is {{ birthday | date }}</p>`
})
export class UserBirthdayComponent {
  birthday = new Date(1981, 3, 15); 
}

What is angular routing?

The Angular Router enables navigation from one view to the other as users perform application tasks.

Angular router interpret a browser URL to navigate to a client-generated view. It also can pass parameters along to the supporting view component that help it decide dynamic content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link.

How to check the Angular version installed?

For angular 4+, use one of the below commands.

  • ng version,
  • ng -v.
Explain the structure of Angular application projects.

For instance, take the structure of Shopper Stop angular application.

e2e folder holds end to end test cases that help ensure the angular components are working correctly. This subfolder stores configuration and source files for a set of end-to-end tests that correspond to angular application.

node_modules subfolder provides/stores the npm packages required for the application.

src subfolder contains the source files related to app logic, data, and assets, along with configuration files for the initial application.

.editorconfig configuration file stores editor configuration.

.gitignore file specifies untracked files that Git should ignore.

angular.json stores CLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses.

package-lock.json provides version information for all packages installed into node_modules by the npm client.

package.json configures npm package dependencies that are available to all projects in the workspace.

README.md contains introductory documentation.

tsconfig.json has default TypeScript configuration for apps in the workspace, including TypeScript and Angular template compiler options.

tslint.json stores default TSLint configuration for apps in the workspace.

Structure of src sub-folder.

app/ contains the component files in which your app logic and data are defined.

assets/ contains image files and other asset files to be copied as-is when you build your application.

environments/ contains build configuration options for particular target environments. By default, there is an unnamed standard development environment and a production ("prod") environment. You can define additional target environment configurations.

browserlist configures sharing of target browsers and Node.js versions among various front-end tools.

favicon.ico is the icon to use for this app in the bookmark bar.

index.html is the main HTML page that is served when someone visits your angular site.

main.ts is the main entry point for your app. This typescript file compiles the application with the JIT compiler and bootstraps the application's root module (AppModule) to run in the browser.

polyfills.ts provides polyfill scripts for browser support.

styles.sass lists CSS files that supply styles for a project. The extension reflects the style preprocessor you have configured for the project.

test.ts is the main entry point for your unit tests, with some Angular-specific configuration.

tsconfig.app.json inherits from the workspace-wide tsconfig.json file.

tsconfig.spec.json inherits from the workspace-wide tsconfig.json file.

tslint.json inherits from the workspace-wide tslint.json file.

What is angular CLI?

Angular CLI is a command line interface to scaffold and build angular apps. It provides a scalable project structure and also handles most of the task in building the application.

Angular CLI comes with a handful of commands to set up and build your project from scratch. Below are few commands.

ng new "path_to_project" will create a new project by installing required dependencies.

ng serve builds your project and also it runs the project on the local server.

ng help provides the list of ng commands for reference.

Elements of the Component decorator in Angular.

The Component decorator is an object with many properties such as,

selector specifies the tag (html identifier) used to call this component in HTML templates as any standard HTML tags.

templateUrl specifies HTML template path used to display this component. Alternatively template parameter may be used to include the HTML template inlined as a string.

styleUrls: specifies an list of URLs for CSS style-sheets for the component.

import { Component } from  '@angular/core';
@Component({
    selector:  'app-search',
    templateUrl:  './app.component.html',
    styleUrls: ['./app.component.css']
})
export  class  AppComponent {
    title  =  'Shoppers-stop';
}

Explain Angular services.

Services are a great way to share information among components/classes that don't know each other. Services can be injected into any component and it usually holds data/code providing data for one or more components.

To create a service using angular CLI, use the below command.

ng g service searchAPI

The above command generates 2 files, search-api.service.ts, and search-api.service.spec.ts, hold the code related to service and unit test specification for the service respectively.

search-api.service.ts file generated content follows:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SearchAPIService {

  constructor() { }
}
How do I create a service as a singleton in Angular?

We can create a service as singleton in Angular in 2 ways:

  • Declare that the service should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator as shown below. This is the preferred way to create a singleton service starting Angular 6.

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class UserService {
    }
    
  • Include the service in the AppModule or in a module that is only imported by the AppModule.
What is service worker and its advantages in Angular?

Service worker is a script that runs in a web browser and manages cache of any web application. Angular applications are turned into progressive web application (PWA) after implementing service worker there by benefitted by,

  • increased reliability and performance,
  • eliminate additional low level coding for caching,
  • optimize the end user experience on application over a slow network connection,
  • minimize the risk of serving outdated content.
How does *ngIf directive works?

ngIf directive does not show or hide an element from DOM. Instead, the ngIf directive removes or recreates a portion of the DOM tree based on the ngIf {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise, a clone of the element is reinserted into the DOM.

Angular translates the *ngIf attribute into a <ng-template> element, wrapped around the host element. For example, consider the below code snippet.

<div *ngIf="employee" >{{employee.name}}</div>

This code will be translated as shown below by Angular.

<ng-template [ngIf]="employee">
  <div>{{employee.name}}</div>
</ng-template>
Difference between ng-class and ng-style directives.

ng-style is used to interpolate javascript object into style attribute.

ng-style="{width: 10px}"

The above directive will be translated to style="width:10px".

ng-class directive translates your object into class attribute.

ng-class="{'highlight-class': isActive}"

The above template is translated to class="highlight-class" when isActive variable is true.

Difference between Component and template/templateURL.

In Angular as compared to MVC, a component acts as a controller/ViewModel while template represent the "view".

Default view encapsulation model in Angular.

Emulated view encapsulation is the default encapsulation that emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view.

Types of directives in Angular.

There are 3 types of directives in Angular:

Components, directives with a template.

Structural directives, changes the DOM layout by adding and removing DOM elements. Examples are NgFor and NgIf.

Attribute directives, changes the appearance or behavior of an element, component, or another directive. Examples are NgStyle and NgClass.

What are structural directives in Angular?

Structual directives are responsible for HTML Layouts, reshaping DOM structure by dynamically adding and removing/manipulating elements.

Structural directives have *(asterisk) preceding the attribute name and no square brackets nor parenthesis. This makes structural directives easy to identify.

Examples for structural directives are as follows.

  • *ngIf,
  • *ngFor,
  • ngSwitch (*ngSwitchCase and *ngSwitchDefault).
Difference between Structural and attribute directives.
Structural directive.Attribute directive.
Structural directives are responsible for HTML layout. They shape and modify the DOM's structure by adding, removing, or manipulating elements. .Attribute directive are used as element attributes that change the appearance or behavior of an element, component, or another directive. .
You can only apply one structural directive to a host element.You can apply many attribute directives to one host element.
*ngIf and *ngFor are examples.ngStyle and ngClass are builtin attribute directives.
What is <ng-template> in Angular?

The <ng-template> is an angular element for rendering HTML. It will never get displayed directly in the view. Before rendering the view, Angular replaces the <ng-template> and its contents with a comment.

Explain <ng-container> element in Angular.

The Angular <ng-container> is a grouping element that does NOT interfere with styles or layout because Angular doesn't put this element in the DOM.

The <ng-container> is a syntax element recognized by the Angular parser. It is not a directive, component, class, or interface. This element can replace a span tag as you may want to eliminate any styles associated with the span element, also ng-container can be used for conditional select-option list. In short, use <ng-container> as a grouping element when there is no suitable host element.

Name a few builtin pipes in Angular that you are aware of.

Angular comes with builtin pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe.

What are the different types of Pipes in Angular?

There are 2 types of pipes: pure and impure. Pipes are pure by default. You make a pipe impure by setting its pure flag to false.

@Pipe({
  name: 'exponential',
  pure: false
})

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value such as String, Number, Boolean, Symbol or a changed object reference like Date, Array, Function or Object.

Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, even for every keystroke or mouse movement. Implement an impure pipe with great care since an expensive, long-running pipe could affect performance and user experience.

What is JsonPipe?

JsonPipe is an inbuilt pipe that converts a value/object into its JSON-format representation. It is usually used for debugging.

{{ value_expression | json }}

<form [formGroup] = "profileForm" >
  <label>
First Name: <input type="text" formControlName = "firstName"></label>
<label>Last Name: <input type="text" formControlName ="lastName"></label>

<div formGroupName="address">
<h4>Address</h4>
<label>Street:
<input type="text" formControlName = "street">
</label>
<label>City:
<input type="text" formControlName="city">
</label>
<label>State:
  <input type="text" formControlName="state">
  </label>
  <label>Zip:
    <input type="text" formControlName="zip">
  </label>

</div>
  
<button type="submit" (click)="onsubmit()" [disabled]="!profileForm.valid"> Submit</button> 
</form>
 {{profileForm.value}}

 {{profileForm.value | json }}

What are the methods in Angular FormBuilder?

The FormBuilder service is an injectable provider that is provided with the reactive forms module.

The FormBuilder service has 3 methods: control(), group(), and array(). These are factory methods for generating instances in your component classes including form controls, form groups, and form arrays.

What is ngForm directive?

The NgForm directive powers the form element with additional features. It holds the controls you created for the elements with a ngModel directive and name attribute, monitors their properties and its validity.

<form  #myForm="ngForm">

You must define name attribute when using [(ngModel)] in combination with a form.

What are the child classes of AbstractControl?

AbstractControl is the base class for FormControl, FormGroup, and FormArray.

Difference between Promises and Observable.

Promise.Observable.
A Promise handles only one event when an async operation completes or fails.An Observable is like a Stream and accepts 0 or more (multiple) events where the callback is called for each event.
Promise doesn't support cancelation.Observables are cancelable.
Promises execute immediately on creation.Observables are declarative and computation does not start until subscription.
Promises provide only one value.Observables provide many values.
Promises push errors to the child promises for error handling. Observables subscribe() is responsible for handling errors that provides centralized and predictable error handling.
What is NGModule?

An NgModule describes how the application components fit together. Every application has at least one Angular module, the root module that you bootstrap to launch the application. By convention, it is usually called AppModule.

The @NgModule decorator identifies AppModule as an NgModule class. @NgModule takes a metadata object that tells Angular how to compile and launch the application.

Reference: Angular IO docs.

Can a Angular component be declared in multiple modules?

No. A component can be declared only in one module and that module be reused by importing it.

Design a game using Angular in which the user should click on the highlighted area to score before it vanishes. Also, it should display score with different levels like easy/medium/difficult.

pleae find the game app in stackbliz.

What is tree shaking in Angular?

Tree shaking is a step as part of the build process in which eliminates/drops code in your project that are not used/referenced anywhere.

What defines an Angular view?

A Angular components and its HTML template together defines an Angular view

Difference between a view, a host view, and an embedded view.

Each component along with its template in Angular is represented as a view.

The embedded view is a view that is created for the view nodes specified in the ng-template. It's like a component view but it doesn't have a wrapper component element and component data like injector

Difference between createEmbeddedView and createComponent in Angular.

createEmbeddedView is used to create a view using TemplateRef. TemplateRef is created by Angular compiler when it encounters ng-template tag in your component HTML. The view created using this method is called an embedded view.

createComponent is used to create a view using ComponentFactory. It is created by Angular compiler when you specify a component in the bootstrap property of the module so that compiler generates a factory for it. The view created using this method is called a host view.

import { Component, ViewContainerRef, ComponentFactoryResolver, NgZone, VERSION, ViewChild } from '@angular/core';

@Component({
  selector: 'hello-world',
  template: `<h1>Hello world!</h1>`,
  styles: [``]
})
export class HelloWorldComponent  {}

@Component({
  selector: 'my-app',
  template: `
      <ng-container #hw></ng-container>
  `,
  styles: ['']
})
export class AppComponent {

  @ViewChild('hw', {read:ViewContainerRef}) vc: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  ngOnInit() {
    const factory = this.resolver.resolveComponentFactory(HelloWorldComponent);
    this.vc.createComponent(factory);
  }
}

Various forms of data binding markup in Angular.

There are 4 forms.

  • {{value}},
  • [property]="value",
  • (event)="handler",
  • [(ng-model)] ="property".

Is ngModel an attribute directive?

Yes. ngModel modifies the behavior of an existing element by setting its display value property and responding to change events.

Mention a few roles of Services in Angular.

Service fetch data from server, also it can be used to validate user inputs.

How do I make a parent component listen for child events?

The parent component may bind to the EventEmitter property of child that emit events and react to those events.

The child's EventEmitter property is an output property decorated with @Output().

«
»
ReactJS

Comments & Discussions