├── .gitignore
├── .idea
├── angular-interview-questions.iml
├── inspectionProfiles
│ └── Project_Default.xml
├── misc.xml
├── modules.xml
└── vcs.xml
├── LICENSE
├── README.md
└── images
├── architecture.png
├── createElement.png
├── customElement.png
├── language-completion.gif
├── language-error.gif
├── language-navigation.gif
└── lifecycle.png
/.gitignore:
--------------------------------------------------------------------------------
1 | *.idea
--------------------------------------------------------------------------------
/.idea/angular-interview-questions.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | true
8 |
9 | false
10 | true
11 |
12 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Angular Interview Questions & Answers
2 |
3 | > Click :star:if you like the project. Pull Request are highly appreciated. Follow me [@SudheerJonna](https://twitter.com/SudheerJonna) for technical updates.
4 |
5 | ### Table of Contents
6 |
7 | | No. | Questions |
8 | |---- | ---------
9 | |1 | [What is Angular Framework?](#what-is-angular-framework)|
10 | |2 | [What is the difference between AngularJS and Angular?](#what-is-the-difference-between-angularjs-and-angular)|
11 | |3 | [What is TypeScript?](#what-is-typescript)|
12 | |4 | [Write a pictorial diagram of Angular architecture?](#write-a-pictorial-diagram-of-angular-architecture)|
13 | |5 | [What are the key components of Angular?](#what-are-the-key-components-of-angular)|
14 | |6 | [What are directives?](#what-are-directives)|
15 | |7 | [What are components?](#what-are-components)|
16 | |8 | [What are the differences between Component and Directive?](#what-are-the-differences-between-component-and-directive)|
17 | |9 | [What is a template?](#what-is-a-template)|
18 | |10| [What is a module?](#what-is-a-module)|
19 | |11| [What are lifecycle hooks available?](#what-are-lifecycle-hooks-available)|
20 | |12| [What is a data binding?](#what-is-a-data-binding)|
21 | |13| [What is metadata?](#what-is-metadata)|
22 | |14| [What is Angular CLI?](#what-is-angular-cli)|
23 | |15| [What is the difference between constructor and ngOnInit?](#what-is-the-difference-between-constructor-and-ngoninit)|
24 | |16| [What is a service](#what-is-a-service)|
25 | |17| [What is dependency injection in Angular?](#what-is-dependency-injection-in-angular)|
26 | |18| [How is Dependency Hierarchy formed?](#how-is-dependency-hierarchy-formed)|
27 | |19| [What is the purpose of async pipe?](#what-is-the-purpose-of-async-pipe)|
28 | |20| [What is the option to choose between inline and external template file?](#what-is-the-option-to-choose-between-inline-and-external-template-file)|
29 | |21| [What is the purpose of *ngFor directive?](#what-is-the-purpose-of-ngfor-directive)|
30 | |22| [What is the purpose of ngIf directive?](#what-is-the-purpose-of-ngif-directive)|
31 | |23| [What happens if you use script tag inside template?](#what-happens-if-you-use-script-tag-inside-template)|
32 | |24| [What is interpolation?](#what-is-interpolation)|
33 | |25| [What are template expressions?](#what-are-template-expressions)|
34 | |26| [What are template statements?](#what-are-template-statements)|
35 | |27| [How do you categorize data binding types?](#how-do-you-categorize-data-binding-types)|
36 | |28| [What are pipes?](#what-are-pipes)|
37 | |29| [What is a parameterized pipe?](#what-is-a-parameterized-pipe)|
38 | |30| [How do you chain pipes?](#how-do-you-chain-pipes)|
39 | |31| [What is a custom pipe?](#what-is-a-custom-pipe)|
40 | |32| [Give an example of custom pipe?](#give-an-example-of-custom-pipe)|
41 | |33| [What is the difference between pure and impure pipe?](#what-is-the-difference-between-pure-and-impure-pipe)|
42 | |34| [What is a bootstrapping module?](#what-is-a-bootstrapping-module)|
43 | |35| [What are observables?](#what-are-observables)|
44 | |36| [What is HttpClient and its benefits?](#what-is-httpclient-and-its-benefits)|
45 | |37| [Explain on how to use HttpClient with an example?](#explain-on-how-to-use-httpclient-with-an-example)|
46 | |38| [How can you read full response?](#how-can-you-read-full-response)|
47 | |39| [How do you perform Error handling?](#how-do-you-perform-error-handling)|
48 | |40| [What is RxJS?](#what-is-rxjs)|
49 | |41| [What is subscribing?](#what-is-subscribing)|
50 | |42| [What is an observable?](#what-is-an-observable)|
51 | |43| [What is an observer?](#what-is-an-observer)|
52 | |44| [What is the difference between promise and observable?](#what-is-the-difference-between-promise-and-observable)|
53 | |45| [What is multicasting?](#what-is-multicasting)|
54 | |46| [How do you perform error handling in observables?](#how-do-you-perform-error-handling-in-observables)|
55 | |47| [What is the short hand notation for subscribe method?](#what-is-the-short-hand-notation-for-subscribe-method)|
56 | |48| [What are the utility functions provided by RxJS?](#what-are-the-utility-functions-provided-by-rxjs)|
57 | |49| [What are observable creation functions?](#what-are-observable-creation-functions)|
58 | |50| [What will happen if you do not supply handler for observer?](#what-will-happen-if-you-do-not-supply-handler-for-observer)|
59 | |51| [What are angular elements?](#what-are-angular-elements)|
60 | |52| [What is the browser support of Angular Elements?](#what-is-the-browser-support-of-angular-elements)|
61 | |53| [What are custom elements?](#what-are-custom-elements)|
62 | |54| [Do I need to bootstrap custom elements?](#do-i-need-to-bootstrap-custom-elements)|
63 | |55| [Explain how custom elements works internally?](#explain-how-custom-elements-works-internally)|
64 | |56| [How to transfer components to custom elements?](#how-to-transfer-components-to-custom-elements)|
65 | |57| [What are the mapping rules between Angular component and custom element?](#what-are-the-mapping-rules-between-angular-component-and-custom-element)|
66 | |58| [How do you define typings for custom elements?](#how-do-you-define-typings-for-custom-elements)|
67 | |59| [What are dynamic components?](#what-are-dynamic-components)|
68 | |60| [What are the various kinds of directives?](#what-are-the-various-kinds-of-directives)|
69 | |61| [How do you create directives using CLI?](#how-do-you-create-directives-using-cli)|
70 | |62| [Give an example for attribute directives?](#give-an-example-for-attribute-directives)|
71 | |63| [What is Angular Router?](#what-is-angular-router)|
72 | |64| [What is the purpose of base href tag?](#what-is-the-purpose-of-base-href-tag)|
73 | |65| [What are the router imports?](#what-are-the-router-imports)|
74 | |66| [What is router outlet?](#what-is-router-outlet)|
75 | |67| [What are router links?](#what-are-router-links)|
76 | |68| [What are active router links?](#what-are-active-router-links)|
77 | |69| [What is router state?](#what-is-router-state)|
78 | |70| [What are router events?](#what-are-router-events)|
79 | |71| [What is activated route?](#what-is-activated-route)|
80 | |72| [How do you define routes?](#how-do-you-define-routes)|
81 | |73| [What is the purpose of Wildcard route?](#what-is-the-purpose-of-wildcard-route)|
82 | |74| [Do I need a Routing Module always?](#do-i-need-a-routing-module-always)|
83 | |75| [What is Angular Universal?](#what-is-angular-universal)|
84 | |76| [What are different types of compilation in Angular?](#what-are-different-types-of-compilation-in-angular)|
85 | |77| [What is JIT?](#what-is-jit)|
86 | |78| [What is AOT?](#what-is-aot)|
87 | |79| [Why do we need compilation process?](#why-do-we-need-compilation-process)|
88 | |80| [What are the advantages with AOT?](#what-are-the-advantages-with-aot)|
89 | |81| [What are the ways to control AOT compilation?](#what-are-the-ways-to-control-aot-compilation)|
90 | |82| [What are the restrictions of metadata?](#what-are-the-restrictions-of-metadata)|
91 | |83| [What are the two phases of AOT?](#what-are-the-two-phases-of-aot)|
92 | |84| [Can I use arrow functions in AOT?](#can-i-use-arrow-functions-in-aot)|
93 | |85| [What is the purpose of metadata json files?](#what-is-the-purpose-of-metadata-json-files)|
94 | |86| [Can I use any javascript feature for expression syntax in AOT?](#can-i-use-any-javascript-feature-for-expression-syntax-in-aot)|
95 | |87| [What is folding?](#what-is-folding)|
96 | |88| [What are macros?](#what-are-macros)|
97 | |89| [Give an example of few metadata errors?](#give-an-example-of-few-metadata-errors)|
98 | |90| [What is metadata rewriting?](#what-is-metadata-rewriting)|
99 | |91| [How do you provide configuration inheritance?](#how-do-you-provide-configuration-inheritance)|
100 | |92| [How do you specify angular template compiler options?](#how-do-you-specify-angular-template-compiler-options)|
101 | |93| [How do you enable binding expression validation?](#how-do-you-enable-binding-expression-validation)|
102 | |94| [What is the purpose of any type cast function?](#what-is-the-purpose-of-any-type-cast-function)|
103 | |95| [What is Non null type assertion operator?](#what-is-non-null-type-assertion-operator)|
104 | |96| [What is type narrowing?](#what-is-type-narrowing)|
105 | |97| [How do you describe various dependencies in angular application?](#how-do-you-describe-various-dependencies-in-angular-application)|
106 | |98| [What is zone?](#what-is-zone)|
107 | |99| [What is the purpose of common module?](#what-is-the-purpose-of-common-module)|
108 | |100| [What is codelyzer?](#what-is-codelyzer)|
109 | |101| [What is angular animation?](#what-is-angular-animation)|
110 | |102| [What are the steps to use animation module?](#what-are-the-steps-to-use-animation-module)|
111 | |103| [What is State function?](#what-is-state-function)|
112 | |104| [What is Style function?](#what-is-style-function)|
113 | |105| [What is the purpose of animate function?](#what-is-the-purpose-of-animate-function)|
114 | |106| [What is transition function?](#what-is-transition-function)|
115 | |107| [How to inject the dynamic script in angular?](#how-to-inject-the-dynamic-script-in-angular)|
116 | |108| [What is a service worker and its role in Angular?](#what-is-a-service-worker-and-its-role-in-angular)|
117 | |109| [What are the design goals of service workers?](#what-are-the-design-goals-of-service-workers)|
118 | |110| [What are the differences between AngularJS and Angular with respect to dependency injection?](#what-are-the-differences-between-angularjs-and-angular-with-respect-to-dependency-injection)|
119 | |111| [What is Angular Ivy?](#what-is-angular-ivy)|
120 | |112| [What are the features included in ivy preview?](#what-are-the-features-included-in-ivy-preview)|
121 | |113| [Can I use AOT compilation with Ivy?](#can-i-use-aot-compilation-with-ivy)|
122 | |114| [What is Angular Language Service?](#what-is-angular-language-service)|
123 | |115| [How do you install angular language service in the project?](#how-do-you-install-angular-language-service-in-the-project)|
124 | |116| [Is there any editor support for Angular Language Service?](#is-there-any-editor-support-for-angular-language-service)|
125 | |117| [Explain the features provided by Angular Language Service?](#explain-the-features-provided-by-angular-language-service)|
126 | |118| [How do you add web workers in your application?](#how-do-you-add-web-workers-in-your-application)|
127 | |119| [What are the limitations with web workers?](#what-are-the-limitations-with-web-workers)|
128 | |120| [What is Angular CLI Builder?](#what-is-angular-cli-builder)|
129 | |121| [What is a builder?](#what-is-a-builder)|
130 | |122| [How do you invoke a builder?](#how-do-you-invoke-a-builder)|
131 | |123| [How do you create app shell in Angular?](#how-do-you-create-app-shell-in-angular)|
132 | |124| [What are the case types in Angular?](#what-are-the-case-types-in-angular)|
133 | |125| [What are the class decorators in Angular?](#what-are-the-class-decorators-in-angular)|
134 |
135 | 1. ### What is Angular Framework?
136 |
137 | Angular is a **TypeScript-based open-source** front-end platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.
138 |
139 | 2. ### What is the difference between AngularJS and Angular?
140 | Angular is a completely revived component-based framework in which an application is a tree of individual components.
141 |
142 | Some of the major difference in tabular form
143 |
144 | | AngularJS | Angular |
145 | |---- | ---------
146 | | It is based on MVC architecture | This is based on Service/Controller |
147 | | This uses use JavaScript to build the application| Introduced the typescript to write the application |
148 | | Based on controllers concept| This is a component based UI approach|
149 | | Not a mobile friendly framework| Developed considering mobile platform|
150 | | Difficulty in SEO friendly application development| Ease to create SEO friendly applications|
151 |
152 | 3. ### What is TypeScript?
153 | 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.
154 | You can install it globally as
155 | ```
156 | npm install -g typescript
157 | ```
158 | Let's see a simple example of TypeScript usage,
159 | ```typescript
160 | function greeter(person: string) {
161 | return "Hello, " + person;
162 | }
163 |
164 | let user = "Sudheer";
165 |
166 | document.body.innerHTML = greeter(user);
167 | ```
168 | The greeter method allows only string type as argument.
169 |
170 | 4. ### Write a pictorial diagram of Angular architecture?
171 | The main building blocks of an Angular application is shown in the below diagram
172 | 
173 |
174 | 5. ### What are the key components of Angular?
175 | Angular has the below key components,
176 | 1. **Component:** These are the basic building blocks of angular application to control HTML views.
177 | 2. **Modules:** An angular module is set of angular basic building blocks like component, directives, services etc. An application is divided into logical pieces and each piece of code is called as "module" which perform a single task.
178 | 3. **Templates:** This represent the views of an Angular application.
179 | 4. **Services:** It is used to create components which can be shared across the entire application.
180 | 5. **Metadata:** This can be used to add more data to an Angular class.
181 |
182 | 6. ### What are directives?
183 | Directives add behaviour to an existing DOM element or an existing component instance.
184 | ```typescript
185 | import { Directive, ElementRef, Input } from '@angular/core';
186 |
187 | @Directive({ selector: '[myHighlight]' })
188 | export class HighlightDirective {
189 | constructor(el: ElementRef) {
190 | el.nativeElement.style.backgroundColor = 'yellow';
191 | }
192 | }
193 | ```
194 |
195 | Now this directive extends HTML element behavior with a yellow background as below
196 | ```html
197 |
Highlight me!
198 | ```
199 |
200 | 7. ### What are components?
201 | Components are the most basic UI building block of an Angular app which formed a tree of Angular components. These components are subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.
202 | Let's see a simple example of Angular component
203 | ```typescript
204 | import { Component } from '@angular/core';
205 |
206 | @Component ({
207 | selector: 'my-app',
208 | template: `
209 |
{{title}}
210 |
Learn Angular6 with examples
211 |
`,
212 | })
213 |
214 | export class AppComponent {
215 | title: string = 'Welcome to Angular world';
216 | }
217 | ```
218 |
219 | 8. ### What are the differences between Component and Directive?
220 | In a short note, A component(@component) is a directive-with-a-template.
221 |
222 | Some of the major differences are mentioned in a tabular form
223 |
224 | | Component | Directive |
225 | |---- | ---------
226 | | To register a component we use @Component meta-data annotation | To register directives we use @Directive meta-data annotation |
227 | | Components are typically used to create UI widgets| Directive is used to add behavior to an existing DOM element |
228 | | Component is used to break up the application into smaller components| Directive is use to design re-usable components|
229 | | Only one component can be present per DOM element | Many directives can be used per DOM element |
230 | | @View decorator or templateurl/template are mandatory | Directive doesn't use View|
231 |
232 | 9. ### What is a template?
233 | A template is a HTML view where you can display data by binding controls to properties of an Angular component. You can store your component's template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator's templateUrl property.
234 | **Using inline template with template syntax,**
235 | ```typescript
236 | import { Component } from '@angular/core';
237 |
238 | @Component ({
239 | selector: 'my-app',
240 | template: '
241 |
242 |
{{title}}
243 |
Learn Angular
244 |
245 | '
246 | })
247 |
248 | export class AppComponent {
249 | title: string = 'Hello World';
250 | }
251 | ```
252 | **Using separate template file such as app.component.html**
253 | ```typescript
254 | import { Component } from '@angular/core';
255 |
256 | @Component ({
257 | selector: 'my-app',
258 | templateUrl: 'app/app.component.html'
259 | })
260 |
261 | export class AppComponent {
262 | title: string = 'Hello World';
263 | }
264 | ```
265 |
266 | 10. ### What is a module?
267 |
268 | Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application.
269 | Lets take an example of **app.module.ts** root module declared with **@NgModule** decorator as below,
270 | ```typescript
271 | import { NgModule } from '@angular/core';
272 | import { BrowserModule } from '@angular/platform-browser';
273 | import { AppComponent } from './app.component';
274 |
275 | @NgModule ({
276 | imports: [ BrowserModule ],
277 | declarations: [ AppComponent ],
278 | bootstrap: [ AppComponent ]
279 | })
280 | export class AppModule { }
281 | ```
282 | The NgModule decorator has three options
283 | 1. The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
284 | 2. The declarations option is used to define components in the respective module
285 | 3. The bootstrap option tells Angular which Component to bootstrap in the application
286 |
287 | 11. ### What are lifecycle hooks available?
288 | Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application.
289 | The representation of lifecycle in pictorial representation as follows,
290 | 
291 |
292 |
293 | The description of each lifecycle method is as below,
294 | 1. **ngOnChanges:** When the value of a data bound property changes, then this method is called.
295 | 2. **ngOnInit:** This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
296 | 3. **ngDoCheck:** This is for the detection and to act on changes that Angular can't or won't detect on its own.
297 | 4. **ngAfterContentInit:** This is called in response after Angular projects external content into the component's view.
298 | 5. **ngAfterContentChecked:** This is called in response after Angular checks the content projected into the component.
299 | 6. **ngAfterViewInit:** This is called in response after Angular initializes the component's views and child views.
300 | 7. **ngAfterViewChecked:** This is called in response after Angular checks the component's views and child views.
301 | 8. **ngOnDestroy:** This is the cleanup phase just before Angular destroys the directive/component.
302 |
303 | 12. ### What is a data binding?
304 | Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding(divided as 3 categories) which differ in the way the data is flowing.
305 | 1. **From the Component to the DOM:**
306 | **Interpolation:** {{ value }}: Adds the value of a property from the component
307 | ```html
308 |
Name: {{ user.name }}
309 |
Address: {{ user.address }}
310 | ```
311 | **Property binding:** [property]=”value”: The value is passed from the component to the specified property or simple HTML attribute
312 | ```html
313 |
314 | ```
315 | 2. **From the DOM to the Component:**
316 | **Event binding: (event)=”function”:** When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component
317 | ```html
318 |
319 | ```
320 | 3. **Two-way binding:**
321 | **Two-way data binding:** [(ngModel)]=”value”: Two-way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync
322 | ```html
323 |
324 | ```
325 |
326 | 13. ### What is metadata?
327 | Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators
328 | 1. **Class decorators**, e.g. @Component and @NgModule
329 | ```typescript
330 | import { NgModule, Component } from '@angular/core';
331 |
332 | @Component({
333 | selector: 'my-component',
334 | template: '
Class decorator
',
335 | })
336 | export class MyComponent {
337 | constructor() {
338 | console.log('Hey I am a component!');
339 | }
340 | }
341 |
342 | @NgModule({
343 | imports: [],
344 | declarations: [],
345 | })
346 | export class MyModule {
347 | constructor() {
348 | console.log('Hey I am a module!');
349 | }
350 | }
351 | ```
352 | 2. **Property decorators** Used for properties inside classes, e.g. @Input and @Output
353 | ```typescript
354 | import { Component, Input } from '@angular/core';
355 |
356 | @Component({
357 | selector: 'my-component',
358 | template: '
'
373 | })
374 | export class MyComponent {
375 | @HostListener('click', ['$event'])
376 | onHostClick(event: Event) {
377 | // clicked, `event` available
378 | }
379 | }
380 | ```
381 | 4. **Parameter decorators** Used for parameters inside class constructors, e.g. @Inject
382 | ```typescript
383 | import { Component, Inject } from '@angular/core';
384 | import { MyService } from './my-service';
385 |
386 | @Component({
387 | selector: 'my-component',
388 | template: '
Parameter decorator
'
389 | })
390 | export class MyComponent {
391 | constructor(@Inject(MyService) myService) {
392 | console.log(myService); // MyService
393 | }
394 | }
395 | ```
396 |
397 | 14. ### What is angular CLI?
398 | Angular CLI(**Command Line Interface**) is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules.
399 | You need to install using below npm command,
400 | ```
401 | npm install @angular/cli@latest
402 | ```
403 | Below are the list of few commands, which will come handy while creating angular projects
404 | 1. **Creating New Project:** ng new
405 | 2. **Generating Components, Directives & Services:** ng generate/g
406 | The different types of commands would be,
407 | * ng generate class my-new-class: add a class to your application
408 | * ng generate component my-new-component: add a component to your application
409 | * ng generate directive my-new-directive: add a directive to your application
410 | * ng generate enum my-new-enum: add an enum to your application
411 | * ng generate module my-new-module: add a module to your application
412 | * ng generate pipe my-new-pipe: add a pipe to your application
413 | * ng generate service my-new-service: add a service to your application
414 | 3. **Running the Project:** ng serve
415 |
416 | 15. ### What is the difference between constructor and ngOnInit?
417 | TypeScript classes has a default method called constructor which is normally used for the initialization purpose. Whereas ngOnInit method is specific to Angular, especially used to define Angular bindings. Even though constructor getting called first, it is preferred to move all of your Angular bindings to ngOnInit method.
418 | In order to use ngOnInit, you need to implement OnInit interface as below,
419 | ```typescript
420 | export class App implements OnInit{
421 | constructor(){
422 | //called first time before the ngOnInit()
423 | }
424 |
425 | ngOnInit(){
426 | //called after the constructor and called after the first ngOnChanges()
427 | }
428 | }
429 | ```
430 | 16. ### What is a service?
431 | 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.
432 | Let's create a repoService which can be used across components,
433 | ```typescript
434 | import { Injectable } from '@angular/core';
435 | import { Http } from '@angular/http';
436 |
437 | @Injectable({ // The Injectable decorator is required for dependency injection to work
438 | // providedIn option registers the service with a specific NgModule
439 | providedIn: 'root', // This declares the service with the root app (AppModule)
440 | })
441 | export class RepoService{
442 | constructor(private http: Http){
443 | }
444 |
445 | fetchAll(){
446 | return this.http.get('https://api.github.com/repositories');
447 | }
448 | }
449 | ```
450 | The above service uses Http service as a dependency.
451 |
452 | 17. ### What is dependency injection in Angular?
453 | Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.
454 |
455 | 18. ### How is Dependency Hierarchy formed?
456 |
457 | 19. ### What is the purpose of async pipe?
458 | The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes.
459 | Let's take a time observable which continuously updates the view for every 2 seconds with the current time.
460 | ```typescript
461 | @Component({
462 | selector: 'async-observable-pipe',
463 | template: `
observable|async:
464 | Time: {{ time | async }}
`
465 | })
466 | export class AsyncObservablePipeComponent {
467 | time = new Observable(observer =>
468 | setInterval(() => observer.next(new Date().toString()), 2000)
469 | );
470 | }
471 | ```
472 | 20. ### What is the option to choose between inline and external template file?
473 | You can store your component's template in one of two places. You can define it inline using the **template** property, or you can define the template in a separate HTML file and link to it in the component metadata using the **@Component** decorator's **templateUrl** property.
474 | The choice between inline and separate HTML is a matter of taste, circumstances, and organization policy. But normally we use inline template for small portion of code and external template file for bigger views. By default, the Angular CLI generates components with a template file. But you can override that with the below command,
475 | ```
476 | ng generate component hero -it
477 | ```
478 | 21. ### What is the purpose of ngFor directive?
479 | We use Angular ngFor directive in the template to display each item in the list. For example, here we iterate over list of users,
480 | ```html
481 |
482 | {{ user }}
483 |
484 | ```
485 | The user variable in the ngFor double-quoted instruction is a **template input variable**
486 | 22. ### What is the purpose of ngIf directive?
487 | Sometimes an app needs to display a view or a portion of a view only under specific circumstances. The Angular ngIf directive inserts or removes an element based on a truthy/falsy condition. Let's take an example to display a message if the user age is more than 18,
488 | ```html
489 |
18">You are not eligible for student pass!
490 | ```
491 | **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.
492 |
493 | 23. ### What happens if you use script tag inside template?
494 |
495 | Angular recognizes the value as unsafe and automatically sanitizes it, which removes the ** Syntax';
501 | }
502 | ```
503 |
504 | 24. ### What is interpolation?
505 |
506 | Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding. It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property.
507 | Let's take an example,
508 | ```html
509 |
510 | {{title}}
511 |
512 |
513 | ```
514 | 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.
515 |
516 | 25. ### What are template expressions?
517 | A template expression produces a value similar to any Javascript expression. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive. In the property binding, a template expression appears in quotes to the right of the = symbol as in [property]="expression".
518 | In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}},
519 | ```html
520 |
{{username}}, welcome to Angular
521 | ```
522 | The below javascript expressions are prohibited in template expression
523 | 1. assignments (=, +=, -=, ...)
524 | 2. new
525 | 3. chaining expressions with ; or ,
526 | 4. increment and decrement operators (++ and --)
527 | ----------------------------------
528 | 26. ### What are template statements?
529 | A template statement responds to an event raised by a binding target such as an element, component, or directive. The template statements appear in quotes to the right of the = symbol like **(event)="statement"**. Let's take an example of button click event's statement
530 | ```html
531 |
532 | ```
533 | In the above expression, editProfile is a template statement. The below JavaScript syntax expressions are not allowed.
534 | 1. new
535 | 2. increment and decrement operators, ++ and --
536 | 3. operator assignment, such as += and -=
537 | 4. the bitwise operators | and &
538 | 5. the template expression operators
539 | --------------------------------------
540 | 27. ### How do you categorize data binding types?
541 |
542 | Binding types can be grouped into three categories distinguished by the direction of data flow. They are listed as below,
543 | 1. From the source-to-view
544 | 2. From view-to-source
545 | 3. View-to-source-to-view
546 |
547 | The possible binding syntax can be tabularized as below,
548 |
549 | | Data direction | Syntax | Type |
550 | |---- | --------- | ---- |
551 | | From the source-to-view(One-way) | 1. {{expression}} 2. [target]="expression" 3. bind-target="expression" | Interpolation, Property, Attribute, Class, Style|
552 | | From view-to-source(One-way) | 1. (target)="statement" 2. on-target="statement" | Event |
553 | | View-to-source-to-view(Two-way)| 1. [(target)]="expression" 2. bindon-target="expression"| Two-way |
554 |
555 | 28. ### What are pipes?
556 | A pipe takes in data as input and transforms it to a desired output. For example, let us take a pipe to transform a component's birthday property into a human-friendly date using **date** pipe.
557 | ```javascript
558 | import { Component } from '@angular/core';
559 |
560 | @Component({
561 | selector: 'app-birthday',
562 | template: `
Birthday is {{ birthday | date }}
`
563 | })
564 | export class BirthdayComponent {
565 | birthday = new Date(1987, 6, 18); // June 18, 1987
566 | }
567 | ```
568 | 29. ### What is a parameterized pipe?
569 | A pipe can accept any number of optional parameters to fine-tune its output. The parameterized pipe can be created by declaring the pipe name with a colon ( : ) and then the parameter value. If the pipe accepts multiple parameters, separate the values with colons. Let's take a birthday example with a particular format(dd/mm/yyyy):
570 | ```javascript
571 | import { Component } from '@angular/core';
572 |
573 | @Component({
574 | selector: 'app-birthday',
575 | template: `
Birthday is {{ birthday | date:'dd/mm/yyyy'}}
` // 18/06/1987
576 | })
577 | export class BirthdayComponent {
578 | birthday = new Date(1987, 6, 18);
579 | }
580 | ```
581 | **Note:** The parameter value can be any valid template expression, such as a string literal or a component property.
582 | 30. ### How do you chain pipes?
583 | You can chain pipes together in potentially useful combinations as per the needs. Let's take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below
584 | ```javascript
585 | import { Component } from '@angular/core';
586 |
587 | @Component({
588 | selector: 'app-birthday',
589 | template: `
Birthday is {{ birthday | date:'fullDate' | uppercase}}
` // THURSDAY, JUNE 18, 1987
590 | })
591 | export class BirthdayComponent {
592 | birthday = new Date(1987, 6, 18);
593 | }
594 |
595 | ```
596 | 31. ### What is a custom pipe?
597 | Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,
598 | 1. A pipe is a class decorated with pipe metadata **@Pipe** decorator, which you import from the core Angular library
599 | For example,
600 | ```javascript
601 | @Pipe({name: 'myCustomPipe'})
602 | ```
603 | 2. The pipe class implements the **PipeTransform** interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.
604 | The structure of pipeTransform would be as below,
605 | ```javascript
606 | interface PipeTransform {
607 | transform(value: any, ...args: any[]): any
608 | }
609 | ```
610 | 3. The @Pipe decorator allows you to define the pipe name that you'll use within template expressions. It must be a valid JavaScript identifier.
611 | ```javascript
612 | template: `{{someInputValue | myCustomPipe: someOtherValue}}`
613 | ```
614 | 32. ### Give an example of custom pipe?
615 | You can create custom reusable pipes for the transformation of existing value. For example, let us create a custom pipe for finding file size based on an extension,
616 | ```javascript
617 | import { Pipe, PipeTransform } from '@angular/core';
618 |
619 | @Pipe({name: 'customFileSizePipe'})
620 | export class FileSizePipe implements PipeTransform {
621 | transform(size: number, extension: string = 'MB'): string {
622 | return (size / (1024 * 1024)).toFixed(2) + extension;
623 | }
624 | }
625 | ```
626 | Now you can use the above pipe in template expression as below,
627 | ```javascript
628 | template: `
629 |
Find the size of a file
630 |
Size: {{288966 | customFileSizePipe: 'GB'}}
631 | `
632 | ```
633 | 33. ### What is the difference between pure and impure pipe?
634 | A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object). An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.
635 | 34. ### What is a bootstrapping module?
636 | Every application has at least one Angular module, the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule. The default structure of AppModule generated by AngularCLI would be as follows,
637 | ```javascript
638 | /* JavaScript imports */
639 | import { BrowserModule } from '@angular/platform-browser';
640 | import { NgModule } from '@angular/core';
641 | import { FormsModule } from '@angular/forms';
642 | import { HttpClientModule } from '@angular/common/http';
643 |
644 | import { AppComponent } from './app.component';
645 |
646 | /* the AppModule class with the @NgModule decorator */
647 | @NgModule({
648 | declarations: [
649 | AppComponent
650 | ],
651 | imports: [
652 | BrowserModule,
653 | FormsModule,
654 | HttpClientModule
655 | ],
656 | providers: [],
657 | bootstrap: [AppComponent]
658 | })
659 | export class AppModule { }
660 | ```
661 | 35. ### What are observables?
662 | Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.
663 | 36. ### What is HttpClient and its benefits?
664 | Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as **HttpClient** which is based on top of XMLHttpRequest interface. This client is avaialble from `@angular/common/http` package.
665 | You can import in your root module as below,
666 | ```javascript
667 | import { HttpClientModule } from '@angular/common/http';
668 | ```
669 |
670 | The major advantages of HttpClient can be listed as below,
671 | 1. Contains testability features
672 | 2. Provides typed request and response objects
673 | 3. Intercept request and response
674 | 4. Supports Observalbe APIs
675 | 5. Supports streamlined error handling
676 |
677 | 37. ### Explain on how to use HttpClient with an example?
678 | Below are the steps need to be followed for the usage of HttpClient.
679 | 1. Import HttpClient into root module:
680 | ```javascript
681 | import { HttpClientModule } from '@angular/common/http';
682 | @NgModule({
683 | imports: [
684 | BrowserModule,
685 | // import HttpClientModule after BrowserModule.
686 | HttpClientModule,
687 | ],
688 | ......
689 | })
690 | export class AppModule {}
691 | ```
692 | 2. Inject the HttpClient into the application:
693 | Let's create a userProfileService(userprofile.service.ts) as an example. It also defines get method of HttpClient
694 | ```javascript
695 | import { Injectable } from '@angular/core';
696 | import { HttpClient } from '@angular/common/http';
697 |
698 | const userProfileUrl: string = 'assets/data/profile.json';
699 |
700 | @Injectable()
701 | export class UserProfileService {
702 | constructor(private http: HttpClient) { }
703 |
704 | getUserProfile() {
705 | return this.http.get(this.userProfileUrl);
706 | }
707 | }
708 | ```
709 | 3. Create a component for subscribing service:
710 | Let's create a component called UserProfileComponent(userprofile.component.ts) which inject UserProfileService and invokes the service method,
711 | ```javascript
712 | fetchUserProfile() {
713 | this.userProfileService.getUserProfile()
714 | .subscribe((data: User) => this.user = {
715 | id: data['userId'],
716 | name: data['firstName'],
717 | city: data['city']
718 | });
719 | }
720 | ```
721 | Since the above service method returns an Observable which needs to be subscribed in the component.
722 | 38. ### How can you read full response?
723 | The response body doesn't may not return full response data because sometimes servers also return special headers or status code which which are important for the application workflow. Inorder to get full response, you should use observe option from HttpClient,
724 | ```javascript
725 | getUserResponse(): Observable> {
726 | return this.http.get(
727 | this.userUrl, { observe: 'response' });
728 | }
729 | ```
730 | Now HttpClient.get() method returns an Observable of typed HttpResponse rather than just the JSON data.
731 | 39. ### How do you perform Error handling?
732 | If the request fails on the server or failed to reach the server due to network issues then HttpClient will return an error object instead of a successful reponse. In this case, you need to handle in the component by passing error object as a second callback to subscribe() method.
733 | Let's see how it can be handled in the component with an example,
734 | ```javascript
735 | fetchUser() {
736 | this.userService.getProfile()
737 | .subscribe(
738 | (data: User) => this.userProfile = { ...data }, // success path
739 | error => this.error = error // error path
740 | );
741 | }
742 | ```
743 | It is always a good idea to give the user some meaningful feedback instead of displaying the raw error object returned from HttpClient.
744 | 40. ### What is RxJS?
745 | RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables.
746 | For example, you can import observables and operators for using HttpClient as below,
747 | ```javascript
748 | import { Observable, throwError } from 'rxjs';
749 | import { catchError, retry } from 'rxjs/operators';
750 | ```
751 | 41. ### What is subscribing?
752 | An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the **subscribe()** method of the instance, passing an observer object to receive the notifications.
753 | Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.
754 | ```javascript
755 | Creates an observable sequence of 5 integers, starting from 1
756 | const source = range(1, 5);
757 |
758 | // Create observer object
759 | const myObserver = {
760 | next: x => console.log('Observer got a next value: ' + x),
761 | error: err => console.error('Observer got an error: ' + err),
762 | complete: () => console.log('Observer got a complete notification'),
763 | };
764 |
765 | // Execute with the observer object and Prints out each item
766 | myObservable.subscribe(myObserver);
767 | // => Observer got a next value: 1
768 | // => Observer got a next value: 2
769 | // => Observer got a next value: 3
770 | // => Observer got a next value: 4
771 | // => Observer got a next value: 5
772 | // => Observer got a complete notification
773 | ```
774 | 42. ### What is an observable?
775 | An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS.
776 | The observables are created using new keyword. Let see the simple example of observable,
777 | ```javascript
778 | import { Observable } from 'rxjs';
779 |
780 | const observable = new Observable(observer => {
781 | setTimeout(() => {
782 | observer.next('Hello from a Observable!');
783 | }, 2000);
784 | });
785 | ```
786 |
787 | 43. ### What is an observer?
788 | Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure,
789 | ```javascript
790 | interface Observer {
791 | closed?: boolean;
792 | next: (value: T) => void;
793 | error: (err: any) => void;
794 | complete: () => void;
795 | }
796 | ```
797 | A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below,
798 | ```javascript
799 | myObservable.subscribe(myObserver);
800 | ```
801 | **Note:** If you don't supply a handler for a notification type, the observer ignores notifications of that type.
802 | 44. ### What is the difference between promise and observable?
803 | Below are the list of differences between promise and observable,
804 |
805 | | Observable | Promise |
806 | |---- | --------- |
807 | | Declarative: Computation does not start until subscription so that they can be run whenever you need the result | Execute immediately on creation|
808 | | Provide multiple values over time | Provide only one |
809 | | Subscribe method is used for error handling which makes centralized and predictable error handling| Push errors to the child promises |
810 | | Provides chaining and subscription to handle complex applications | Uses only .then() clause |
811 |
812 | 45. ### What is multicasting?
813 | Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let's demonstrate the multi-casting feature,
814 | ```javascript
815 | var source = Rx.Observable.from([1, 2, 3]);
816 | var subject = new Rx.Subject();
817 | var multicasted = source.multicast(subject);
818 |
819 | // These are, under the hood, `subject.subscribe({...})`:
820 | multicasted.subscribe({
821 | next: (v) => console.log('observerA: ' + v)
822 | });
823 | multicasted.subscribe({
824 | next: (v) => console.log('observerB: ' + v)
825 | });
826 |
827 | // This is, under the hood, `s
828 | ```
829 | 46. ### How do you perform error handling in observables?
830 | You can handle errors by specifying an **error callback** on the observer instead of relying on try/catch which are ineffective in asynchronous environment. For example, you can define error callback as below,
831 | ```javascript
832 | myObservable.subscribe({
833 | next(num) { console.log('Next num: ' + num)},
834 | error(err) { console.log('Received an errror: ' + err)}
835 | });
836 | ```
837 | 47. ### What is the short hand notation for subscribe method?
838 | The subscribe() method can accept callback function definitions in line, for next, error, and complete handlers is known as short hand notation or Subscribe method with positional arguments. For example, you can define subscribe method as below,
839 | ```javascript
840 | myObservable.subscribe(
841 | x => console.log('Observer got a next value: ' + x),
842 | err => console.error('Observer got an error: ' + err),
843 | () => console.log('Observer got a complete notification')
844 | );
845 | ```
846 | 48. ### What are the utility functions provided by RxJS?
847 | The RxJS library also provides below utility functions for creating and working with observables.
848 | 1. Converting existing code for async operations into observables
849 | 2. Iterating through the values in a stream
850 | 3. Mapping values to different types
851 | 4. Filtering streams
852 | 5. Composing multiple streams
853 | 49. ### What are observable creation functions?
854 | RxJS provides creation functions for the process of creating observables from things such as promises, events, timers and Ajax requests. Let us explain each of them with an example,
855 | 1. Create an observable from a promise
856 | ```javascript
857 | import { from } from 'rxjs'; // from function
858 | const data = from(fetch('/api/endpoint')); //Created from Promise
859 | data.subscribe({
860 | next(response) { console.log(response); },
861 | error(err) { console.error('Error: ' + err); },
862 | complete() { console.log('Completed'); }
863 | });
864 | ```
865 | 2. Create an observable that creates an AJAX request
866 | ```javascript
867 | import { ajax } from 'rxjs/ajax'; // ajax function
868 | const apiData = ajax('/api/data'); // Created from AJAX request
869 | // Subscribe to create the request
870 | apiData.subscribe(res => console.log(res.status, res.response));
871 | ```
872 | 3. Create an observable from a counter
873 | ```javascript
874 | import { interval } from 'rxjs'; // interval function
875 | const secondsCounter = interval(1000); // Created from Counter value
876 | secondsCounter.subscribe(n =>
877 | console.log(`Counter value: ${n}`));
878 | ```
879 | 4. Create an observable from an event
880 | ```javascript
881 | import { fromEvent } from 'rxjs';
882 | const el = document.getElementById('custom-element');
883 | const mouseMoves = fromEvent(el, 'mousemove');
884 | const subscription = mouseMoves.subscribe((e: MouseEvent) => {
885 | console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
886 | });
887 | ```
888 | 50. ### What will happen if you do not supply handler for observer?
889 | Normally an observer object can define any combination of next, error and complete notification type handlers. If you don't supply a handler for a notification type, the observer just ignores notifications of that type.
890 | 51. ### What are angular elements?
891 | Angular elements are Angular components packaged as **custom elements**(a web standard for defining new HTML elements in a framework-agnostic way). Angular Elements hosts an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs, thus, providing a way to use Angular components in `non-Angular environments`.
892 | 52. ### What is the browser support of Angular Elements?
893 | Since Angular elements are packaged as custom elements the browser support of angular elements is same as custom elements support. This feature is is currently supported natively in a number of browsers and pending for other browsers.
894 |
895 | | Browser | Angular Element Support |
896 | |---- | --------- |
897 | | Chrome | Natively supported|
898 | | Opera | Natively supported |
899 | | Safari| Natively supported |
900 | | Firefox | Natively supported from 63 version onwards. You need to enable dom.webcomponents.enabled and dom.webcomponents.customelements.enabled in older browsers |
901 | | Edge| Currently it is in progress|
902 | 53. ### What are custom elements?
903 | Custom elements (or Web Components) are a Web Platform feature which extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code. The browser maintains a `CustomElementRegistry` of defined custom elements, which maps an instantiable JavaScript class to an HTML tag. Currently this feature is supported by Chrome, Firefox, Opera, and Safari, and available in other browsers through polyfills.
904 | 54. ### Do I need to bootstrap custom elements?
905 | No, custom elements bootstrap (or start) automatically when they are added to the DOM, and are automatically destroyed when removed from the DOM. Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular.
906 | 55. ### Explain how custom elements works internally?
907 | Below are the steps in an order about custom elements functionality,
908 | 1. **App registers custom element with browser:** Use the createCustomElement() function to convert a component into a class that can be registered with the browser as a custom element.
909 | 2. **App adds custom element to DOM:** Add custom element just like a built-in HTML element directly into the DOM.
910 | 3. **Browser instantiate component based class:** Browser creates an instance of the registered class and adds it to the DOM.
911 | 4. **Instance provides content with data binding and change detection:** The content with in template is rendered using the component and DOM data.
912 | The flow chart of the custom elements functionality would be as follows,
913 | 
914 | 56. ### How to transfer components to custom elements?
915 | Transforming components to custom elements involves **two** major steps,
916 | 1. **Build custom element class:** Angular provides the `createCustomElement()` function for converting an Angular component (along with its dependencies) to a custom element. The conversion process implements `NgElementConstructor` interface, and creates a constructor class which is used to produce a self-bootstrapping instance of Angular component.
917 | 2. **Register element class with browser:** It uses `customElements.define()` JS function, to register the configured constructor and its associated custom-element tag with the browser's `CustomElementRegistry`. When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance.
918 | The detailed structure would be as follows,
919 | 
920 | 57. ### What are the mapping rules between Angular component and custom element?
921 | The Component properties and logic maps directly into HTML attributes and the browser's event system. Let us describe them in two steps,
922 | 1. The createCustomElement() API parses the component input properties with corresponding attributes for the custom element. For example, component @Input('myInputProp') converted as custom element attribute `my-input-prop`.
923 | 2. The Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name. For example, component @Output() valueChanged = new EventEmitter() converted as custom element with dispatch event as "valueChanged".
924 | 58. ### How do you define typings for custom elements?
925 | You can use the `NgElement` and `WithProperties` types exported from @angular/elements. Let's see how it can be applied by comparing with Angular component,
926 | The simple container with input property would be as below,
927 | ```javascript
928 | @Component(...)
929 | class MyContainer {
930 | @Input() message: string;
931 | }
932 | ```
933 | After applying types typescript validates input value and their types,
934 | ```javascirpt
935 | const container = document.createElement('my-container') as NgElement & WithProperties<{message: string}>;
936 | container.message = 'Welcome to Angular elements!';
937 | container.message = true; // <-- ERROR: TypeScript knows this should be a string.
938 | container.greet = 'News'; // <-- ERROR: TypeScript knows there is no `greet` property on `container`.
939 | ```
940 | 59. ### What are dynamic components?
941 | Dynamic components are the components in which components location in the application is not defined at build time.i.e, They are not used in any angular template. But the component is instantiated and placed in the application at runtime.
942 | 60. ### What are the various kinds of directives?
943 | There are mainly three kinds of directives.
944 | 1. **Components** — These are directives with a template.
945 | 2. **Structural directives** — These directives change the DOM layout by adding and removing DOM elements.
946 | 3. **Attribute directives** — These directives change the appearance or behavior of an element, component, or another directive.
947 | 61. ### How do you create directives using CLI?
948 | You can use CLI command `ng generate directive` to create the directive class file. It creates the source file(src/app/components/directivename.directive.ts), the respective test file(.spec.ts) and declare the directive class file in root module.
949 | 62. ### Give an example for attribute directives?
950 | Let's take simple highlighter behavior as a example directive for DOM element. You can create and apply the attribute directive using below steps,
951 | 1. Create HighlightDirective class with the file name `src/app/highlight.directive.ts`. In this file, we need to import **Directive** from core library to apply the metadata and **ElementRef** in the directive's constructor to inject a reference to the host DOM element ,
952 | ```javascript
953 | import { Directive, ElementRef } from '@angular/core';
954 |
955 | @Directive({
956 | selector: '[appHighlight]'
957 | })
958 | export class HighlightDirective {
959 | constructor(el: ElementRef) {
960 | el.nativeElement.style.backgroundColor = 'red';
961 | }
962 | }
963 | ```
964 | 2. Apply the attribute directive as an attribute to the host element(for example,
)
965 | ```javascript
966 |
Highlight me!
967 | ```
968 | 3. Run the application to see the highlight behavior on paragraph element
969 | ```javascript
970 | ng serve
971 | ```
972 | 63. ### What is Angular Router?
973 | Angular Router is a mechanism in which navigation happens from one view to the next as users perform application tasks. It borrows the concepts or model of browser's application navigation.
974 | 64. ### What is the purpose of base href tag?
975 | The routing application should add element to the index.html as the first child in the tag inorder to indicate how to compose navigation URLs. If app folder is the application root then you can set the href value as below
976 | ```html
977 |
978 | ```
979 | 65. ### What are the router imports?
980 | The Angular Router which represents a particular component view for a given URL is not part of Angular Core. It is available in library named `@angular/router` to import required router components. For example, we import them in app module as below,
981 | ```javascript
982 | import { RouterModule, Routes } from '@angular/router';
983 | ```
984 | 66. ### What is router outlet?
985 | The RouterOutlet is a directive from the router library and it acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. Router outlet is used like a component,
986 | ```html
987 |
988 |
989 | ```
990 | 67. ### What are router links?
991 | The RouterLink is a directive on the anchor tags give the router control over those elements. Since the navigation paths are fixed, you can assign string values to router-link directive as below,
992 | ```html
993 |
Angular Router
994 |
998 |
999 | ```
1000 | 68. ### What are active router links?
1001 | RouterLinkActive is a directive that toggles css classes for active RouterLink bindings based on the current RouterState. i.e, the Router will add CSS classes when this link is active and and remove when the link is inactive. For example, you can add them to RouterLinks as below
1002 | ```html
1003 |
Angular Router
1004 |
1008 |
1009 | ```
1010 | 69. ### What is router state?
1011 | RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. You can access the current RouterState from anywhere in the application using the `Router service` and the `routerState` property.
1012 | ```javascript
1013 | @Component({templateUrl:'template.html'})
1014 | class MyComponent {
1015 | constructor(router: Router) {
1016 | const state: RouterState = router.routerState;
1017 | const root: ActivatedRoute = state.root;
1018 | const child = root.firstChild;
1019 | const id: Observable = child.params.map(p => p.id);
1020 | //...
1021 | }
1022 | }
1023 | ```
1024 | 70. ### What are router events?
1025 | During each navigation, the Router emits navigation events through the Router.events property allowing you to track the lifecycle of the route. The sequence of router events is as below,
1026 | 1. NavigationStart,
1027 | 2. RouteConfigLoadStart,
1028 | 3. RouteConfigLoadEnd,
1029 | 4. RoutesRecognized,
1030 | 5. GuardsCheckStart,
1031 | 6. ChildActivationStart,
1032 | 7. ActivationStart,
1033 | 8. GuardsCheckEnd,
1034 | 9. ResolveStart,
1035 | 10. ResolveEnd,
1036 | 11. ActivationEnd
1037 | 12. ChildActivationEnd
1038 | 13. NavigationEnd,
1039 | 14. NavigationCancel,
1040 | 15. NavigationError
1041 | 16. Scroll
1042 | 71. ### What is activated route?
1043 | ActivatedRoute contains the information about a route associated with a component loaded in an outlet. It can also be used to traverse the router state tree. The ActivatedRoute will be injected as a router service to access the information. In the below example, you can access route path and parameters,
1044 | ```javascript
1045 | @Component({...})
1046 | class MyComponent {
1047 | constructor(route: ActivatedRoute) {
1048 | const id: Observable = route.params.pipe(map(p => p.id));
1049 | const url: Observable = route.url.pipe(map(segments => segments.join('')));
1050 | // route.data includes both `data` and `resolve`
1051 | const user = route.data.pipe(map(d => d.user));
1052 | }
1053 | }
1054 | ```
1055 | 72. ### How do you define routes?
1056 | A router must be configured with a list of route definitions. You configures the router with routes via the `RouterModule.forRoot()` method, and adds the result to the AppModule's `imports` array.
1057 | ```javascript
1058 | const appRoutes: Routes = [
1059 | { path: 'todo/:id', component: TodoDetailComponent },
1060 | {
1061 | path: 'todos',
1062 | component: TodosListComponent,
1063 | data: { title: 'Todos List' }
1064 | },
1065 | { path: '',
1066 | redirectTo: '/todos',
1067 | pathMatch: 'full'
1068 | },
1069 | { path: '**', component: PageNotFoundComponent }
1070 | ];
1071 |
1072 | @NgModule({
1073 | imports: [
1074 | RouterModule.forRoot(
1075 | appRoutes,
1076 | { enableTracing: true } // <-- debugging purposes only
1077 | )
1078 | // other imports here
1079 | ],
1080 | ...
1081 | })
1082 | export class AppModule { }
1083 | ```
1084 | 73. ### What is the purpose of Wildcard route?
1085 | If the URL doesn't match any predefined routes then it causes the router to throw an error and crash the app. In this case, you can use wildcard route. A wildcard route has a path consisting of two asterisks to match every URL.
1086 | For example, you can define PageNotFoundComponent for wildcard route as below
1087 | ```javascript
1088 | { path: '**', component: PageNotFoundComponent }
1089 | ```
1090 | 74. ### Do I need a Routing Module always?
1091 | No, the Routing Module is a design choice. You can skip routing Module (for example, AppRoutingModule) when the configuration is simple and merge the routing configuration directly into the companion module (for example, AppModule). But it is recommended when the configuration is complex and includes specialized guard and resolver services.
1092 | 75. ### What is Angular Universal?
1093 | Angular Universal is a server-side rendering module for Angular applications in various scenarios. This is a community driven project and available under @angular/platform-server package. Recently Angular Universal is integrated with Angular CLI.
1094 | 76. ### What are different types of compilation in Angular?
1095 | Angular offers two ways to compile your application,
1096 | 1. Just-in-Time (JIT)
1097 | 2. Ahead-of-Time (AOT)
1098 | 77. ### What is JIT?
1099 | Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at runtime. JIT compilation is the default when you run the ng build (build only) or ng serve (build and serve locally) CLI commands. i.e, the below commands used for JIT compilation,
1100 | ```javascript
1101 | ng build
1102 | ng serve
1103 | ```
1104 | 78. ### What is AOT?
1105 | Ahead-of-Time (AOT) is a type of compilation that compiles your app at build time. For AOT compilation, include the `--aot` option with the ng build or ng serve command as below,
1106 | ```javascript
1107 | ng build --aot
1108 | ng serve --aot
1109 | ```
1110 | **Note:** The ng build command with the --prod meta-flag (`ng build --prod`) compiles with AOT by default.
1111 | 79. ### Why do we need compilation process?
1112 | The Angular components and templates cannot be understood by the browser directly. Due to that Angular applications require a compilation process before they can run in a browser. For example, In AOT compilation, both Angular HTML and TypeScript code converted into efficient JavaScript code during the build phase before browser runs it.
1113 | 80. ### What are the advantages with AOT?
1114 | Below are the list of AOT benefits,
1115 | 1. **Faster rendering:** The browser downloads a pre-compiled version of the application. So it can render the application immediately without compiling the app.
1116 | 2. **Fewer asynchronous requests:** It inlines external HTML templates and CSS style sheets within the application javascript which eliminates separate ajax requests.
1117 | 3. **Smaller Angular framework download size:** Doesn't require downloading the Angular compiler. Hence it dramatically reduces the application payload.
1118 | 4. **Detect template errors earlier:** Detects and reports template binding errors during the build step itself
1119 | 5. **Better security:** It compiles HTML templates and components into JavaScript. So there won't be any injection attacks.
1120 |
1121 | 81. ### What are the ways to control AOT compilation?
1122 | You can control your app compilation in two ways
1123 | 1. By providing template compiler options in the `tsconfig.json` file
1124 | 2. By configuring Angular metadata with decorators
1125 |
1126 | 82. ### What are the restrictions of metadata?
1127 | In Angular, You must write metadata with the following general constraints,
1128 | 1. Write expression syntax with in the supported range of javascript features
1129 | 2. The compiler can only reference symbols which are exported
1130 | 3. Only call the functions supported by the compiler
1131 | 4. Decorated and data-bound class members must be public.
1132 |
1133 | 83. ### What are the two phases of AOT?
1134 | The AOT compiler works in three phases,
1135 | 1. **Code Analysis:** The compiler records a representation of the source
1136 | 2. **Code generation:** It handles the interpretation as well as places restrictions on what it interprets.
1137 | 3. **Validation:** In this phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates.
1138 |
1139 | 84. ### Can I use arrow functions in AOT?
1140 | No, Arrow functions or lambda functions can’t be used to assign values to the decorator properties. For example, the following snippet is invalid:
1141 | ```javascript
1142 | @Component({
1143 | providers: [{
1144 | provide: MyService, useFactory: () => getService()
1145 | }]
1146 | })
1147 | ```
1148 | To fix this, it has to be changed as following exported function:
1149 | ```javascript
1150 | function getService(){
1151 | return new MyService();
1152 | }
1153 |
1154 | @Component({
1155 | providers: [{
1156 | provide: MyService, useFactory: getService
1157 | }]
1158 | })
1159 | ```
1160 | 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.
1161 | **Note:** From Angular5 onwards, the compiler automatically performs this rewriting while emitting the .js file.
1162 |
1163 | 85. ### What is the purpose of metadata json files?
1164 | The metadata.json file can be treated as a diagram of the overall structure of a decorator's metadata, represented as an abstract syntax tree(AST). During the analysis phase, the AOT collector scan the metadata recorded in the Angular decorators and outputs metadata information in .metadata.json files, one per .d.ts file.
1165 | 86. ### Can I use any javascript feature for expression syntax in AOT?
1166 | No, the AOT collector understands a subset of (or limited) JavaScript features. If an expression uses unsupported syntax, the collector writes an error node to the .metadata.json file. Later point of time, the compiler reports an error if it needs that piece of metadata to generate the application code.
1167 | 87. ### What is folding?
1168 | The compiler can only resolve references to exported symbols in the metadata. Where as some of the non-exported members are folded while generating the code. i.e Folding is a process in which the collector evaluate an expression during collection and record the result in the .metadata.json instead of the original expression.
1169 | For example, the compiler couldn't refer selector reference because it is not exported
1170 | ```javascript
1171 | let selector = 'app-root';
1172 | @Component({
1173 | selector: selector
1174 | })
1175 | ```
1176 | Will be folded into inline selector
1177 | ```javascript
1178 | @Component({
1179 | selector: 'app-root'
1180 | })
1181 | ```
1182 | Remember that the compiler can’t fold everything. For example, spread operator on arrays, objects created using new keywords and function calls.
1183 | 88. ### What are macros?
1184 | The AOT compiler supports macros in the form of functions or static methods that return an expression in a `single return expression`.
1185 | For example, let us take a below macro function,
1186 | ```javascript
1187 | export function wrapInArray(value: T): T[] {
1188 | return [value];
1189 | }
1190 | ```
1191 | You can use it inside metadata as an expression,
1192 | ```javascript
1193 | @NgModule({
1194 | declarations: wrapInArray(TypicalComponent)
1195 | })
1196 | export class TypicalModule {}
1197 | ```
1198 | The compiler treats the macro expression as it written directly
1199 | ```javascript
1200 | @NgModule({
1201 | declarations: [TypicalComponent]
1202 | })
1203 | export class TypicalModule {}
1204 | ```
1205 | 89. ### Give an example of few metadata errors?
1206 | Below are some of the errors encountered in metadata,
1207 | 1. **Expression form not supported:** Some of the language features outside of the compiler's restricted expression syntax used in angular metadata can produce this error.
1208 | Let's see some of these examples,
1209 | ```javascript
1210 | 1. export class User { ... }
1211 | const prop = typeof User; // typeof is not valid in metadata
1212 | 2. { provide: 'token', useValue: { [prop]: 'value' } }; // bracket notation is not valid in metadata
1213 | ```
1214 | 2. ** Reference to a local (non-exported) symbol:** The compiler encountered a referenced to a locally defined symbol that either wasn't exported or wasn't initialized.
1215 | Let's take example of this error,
1216 | ```javascript
1217 | // ERROR
1218 | let username: string; // neither exported nor initialized
1219 |
1220 | @Component({
1221 | selector: 'my-component',
1222 | template: ... ,
1223 | providers: [
1224 | { provide: User, useValue: username }
1225 | ]
1226 | })
1227 | export class MyComponent {}
1228 | ```
1229 | You can fix this by either exporting or initializing the value,
1230 | ```javascript
1231 | export let username: string; // exported
1232 | (or)
1233 | let username = 'John'; // initialized
1234 | ```
1235 | 3. **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.
1236 | ```javascript
1237 | providers: [
1238 | { provide: MyStrategy, useFactory: function() { ... } },
1239 | { provide: OtherStrategy, useFactory: () => { ... } }
1240 | ]
1241 | ```
1242 | You can fix this with exported function
1243 | ```javascript
1244 | export function myStrategy() { ... }
1245 | export function otherStrategy() { ... }
1246 | ... // metadata
1247 | providers: [
1248 | { provide: MyStrategy, useFactory: myStrategy },
1249 | { provide: OtherStrategy, useFactory: otherStrategy },
1250 | ```
1251 | 4. **Destructured variable or constant not supported:** The compiler does not support references to variables assigned by destructuring.
1252 | For example, you cannot write something like this:
1253 | ```javascript
1254 | import { user } from './user';
1255 |
1256 | // destructured assignment to name and age
1257 | const {name, age} = user;
1258 | ... //metadata
1259 | providers: [
1260 | {provide: Name, useValue: name},
1261 | {provide: Age, useValue: age},
1262 | ]
1263 | ```
1264 | You can fix this by non-destructured values
1265 | ```javscript
1266 | import { user } from './user';
1267 | ... //metadata
1268 | providers: [
1269 | {provide: Name, useValue: user.name},
1270 | {provide: Age, useValue: user.age},
1271 | ]
1272 | ```
1273 | 90. ### What is metadata rewriting?
1274 | Metadata rewriting is the process in which the compiler converts the expression initializing the fields such as useClass, useValue, useFactory, and data into an exported variable, which replaces the expression. Remember that the compiler does this rewriting during the emit of the .js file but not in definition files( .d.ts file).
1275 | 91. ### How do you provide configuration inheritance?
1276 | Angular Compiler supports configuration inheritance through extends in the tsconfig.json on angularCompilerOptions. i.e, The configuration from the base file(for example, tsconfig.base.json) are loaded first, then overridden by those in the inheriting config file.
1277 | ```javascript
1278 | {
1279 | "extends": "../tsconfig.base.json",
1280 | "compilerOptions": {
1281 | "experimentalDecorators": true,
1282 | ...
1283 | },
1284 | "angularCompilerOptions": {
1285 | "fullTemplateTypeCheck": true,
1286 | "preserveWhitespaces": true,
1287 | ...
1288 | }
1289 | }
1290 | ```
1291 | 92. ### How do you specify angular template compiler options?
1292 | The angular template compiler options are specified as members of the **angularCompilerOptions** object in the tsconfig.json file. These options will be specified adjecent to typescript compiler options.
1293 | ```javascript
1294 | {
1295 | "compilerOptions": {
1296 | "experimentalDecorators": true,
1297 | ...
1298 | },
1299 | "angularCompilerOptions": {
1300 | "fullTemplateTypeCheck": true,
1301 | "preserveWhitespaces": true,
1302 | ...
1303 | }
1304 | }
1305 | ```
1306 | 93. ### How do you enable binding expression validation?
1307 | You can enable binding expression validation explicitly by adding the compiler option **fullTemplateTypeCheck** in the "angularCompilerOptions" of the project's tsconfig.json. It produces error messages when a type error is detected in a template binding expression.
1308 | For example, consider the following component:
1309 | ```javascript
1310 | @Component({
1311 | selector: 'my-component',
1312 | template: '{{user.contacts.email}}'
1313 | })
1314 | class MyComponent {
1315 | user?: User;
1316 | }
1317 | ```
1318 | This will produce the following error:
1319 | ```javascript
1320 | my.component.ts.MyComponent.html(1,1): : Property 'contacts' does not exist on type 'User'. Did you mean 'contact'?
1321 | ```
1322 | 94. ### What is the purpose of any type cast function?
1323 | You can disable binding expression type checking using $any() type cast function(by surrounding the expression). In the following example, the error Property contacts does not exist is suppressed by casting user to the any type.
1324 | ```javascript
1325 | template: '{{$any(user).contacts.email}}'
1326 | ```
1327 | The $any() cast function also works with this to allow access to undeclared members of the component.
1328 | ```javascript
1329 | template: '{{$any(this).contacts.email}}'
1330 | ```
1331 | 95. ### What is Non null type assertion operator?
1332 | You can use the non-null type assertion operator to suppress the Object is possibly 'undefined' error. In the following example, the user and contact properties are always set together, implying that contact is always non-null if user is non-null. The error is suppressed in the example by using contact!.email.
1333 | ```javascript
1334 | @Component({
1335 | selector: 'my-component',
1336 | template: ' {{user.name}} contacted through {{contact!.email}} '
1337 | })
1338 | class MyComponent {
1339 | user?: User;
1340 | contact?: Contact;
1341 |
1342 | setData(user: User, contact: Contact) {
1343 | this.user = user;
1344 | this.contact = contact;
1345 | }
1346 | }
1347 | ```
1348 | 96. ### What is type narrowing?
1349 | The expression used in an ngIf directive is used to narrow type unions in the Angular template compiler similar to if expression in typescript. So *ngIf allows the typeScript compiler to infer that the data used in the binding expression will never be undefined.
1350 | ```javascript
1351 | @Component({
1352 | selector: 'my-component',
1353 | template: ' {{user.contact.email}} '
1354 | })
1355 | class MyComponent {
1356 | user?: User;
1357 | }
1358 | ```
1359 | 97. ### How do you describe various dependencies in angular application?
1360 | The dependencies section of package.json with in an angular application can be divided as follow,
1361 | 1. **Angular packages:** Angular core and optional modules; their package names begin @angular/.
1362 | 2. **Support packages:** Third-party libraries that must be present for Angular apps to run.
1363 | 3. **Polyfill packages:** Polyfills plug gaps in a browser's JavaScript implementation.
1364 | 98. ### What is zone?
1365 | A Zone is an execution context that persists across async tasks. Angular relies on zone.js to run Angular's change detection processes when native JavaScript operations raise events
1366 | 99. ### What is the purpose of common module?
1367 | The commonly-needed services, pipes, and directives provided by @angular/common module. Apart from these HttpClientModule is available under @angular/common/http.
1368 | 100. ### What is codelyzer?
1369 | Codelyzer provides set of tslint rules for static code analysis of Angular TypeScript projects. ou can run the static code analyzer over web apps, NativeScript, Ionic etc. Angular CLI has support for this and it can be use as below,
1370 | ```javascript
1371 | ng new codelyzer
1372 | ng lint
1373 | ```
1374 | 101. ### What is angular animation?
1375 | 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.
1376 | 102. ### What are the steps to use animation module?
1377 | You need to follow below steps to implement animation in your angular project,
1378 |
1379 | 1. **Enabling the animations module:** Import BrowserAnimationsModule to add animation capabilities into your Angular root application module(for example, src/app/app.module.ts).
1380 | ```javascript
1381 | import { NgModule } from '@angular/core';
1382 | import { BrowserModule } from '@angular/platform-browser';
1383 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
1384 |
1385 | @NgModule({
1386 | imports: [
1387 | BrowserModule,
1388 | BrowserAnimationsModule
1389 | ],
1390 | declarations: [ ],
1391 | bootstrap: [ ]
1392 | })
1393 | export class AppModule { }
1394 | ```
1395 | 2. **Importing animation functions into component files:** Import required animation functions from @angular/animations in component files(for example, src/app/app.component.ts).
1396 | ```javascript
1397 | import {
1398 | trigger,
1399 | state,
1400 | style,
1401 | animate,
1402 | transition,
1403 | // ...
1404 | } from '@angular/animations';
1405 | ```
1406 | 3. **Adding the animation metadata property:** add a metadata property called animations: within the @Component() decorator in component files(for example, src/app/app.component.ts)
1407 | ```javascript
1408 | @Component({
1409 | selector: 'app-root',
1410 | templateUrl: 'app.component.html',
1411 | styleUrls: ['app.component.css'],
1412 | animations: [
1413 | // animation triggers go here
1414 | ]
1415 | })
1416 | ```
1417 | 103. ### What is State function?
1418 | 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.
1419 | For example, you can write a open state function
1420 | ```javascript
1421 | state('open', style({
1422 | height: '300px',
1423 | opacity: 0.5,
1424 | backgroundColor: 'blue'
1425 | })),
1426 | ```
1427 | 104. ### What is Style function?
1428 | The style function is used to define a set of styles to associate with a given state name. You need to use it along with state() function to set CSS style attributes. For example, in the close state, the button has a height of 100 pixels, an opacity of 0.8, and a background color of green.
1429 | ```javascript
1430 | state('close', style({
1431 | height: '100px',
1432 | opacity: 0.8,
1433 | backgroundColor: 'green'
1434 | })),
1435 | ```
1436 | **Note:** The style attributes must be in camelCase
1437 | 105. ### What is the purpose of animate function?
1438 | Angular Animations are a powerful way to implement sophisticated and compelling animations for your Angular single page web application.
1439 |
1440 | ```
1441 | import { Component, OnInit, Input } from '@angular/core';
1442 | import { trigger, state, style, animate, transition } from '@angular/animations';
1443 |
1444 | @Component({
1445 | selector: 'app-animate',
1446 | templateUrl: ``,
1447 | styleUrls: `.myblock {
1448 | background-color: green;
1449 | width: 300px;
1450 | height: 250px;
1451 | border-radius: 5px;
1452 | margin: 5rem;
1453 | }`,
1454 | animations: [
1455 | trigger('changeState', [
1456 | state('state1', style({
1457 | backgroundColor: 'green',
1458 | transform: 'scale(1)'
1459 | })),
1460 | state('state2', style({
1461 | backgroundColor: 'red',
1462 | transform: 'scale(1.5)'
1463 | })),
1464 | transition('*=>state1', animate('300ms')),
1465 | transition('*=>state2', animate('2000ms'))
1466 | ])
1467 | ]
1468 | })
1469 | export class AnimateComponent implements OnInit {
1470 |
1471 | @Input() currentState;
1472 |
1473 | constructor() { }
1474 |
1475 | ngOnInit() {
1476 | }
1477 | }
1478 | ```
1479 | 106. ### What is transition function?
1480 | The animation transition function is used to specify the changes that occur between one state and another over a period of time. It accepts two arguments: the first argument accepts an expression that defines the direction between two transition states, and the second argument accepts an animate() function.
1481 | Let's take an example state transition from open to closed with an half second transition between states.
1482 |
1483 | ```javascript
1484 | transition('open => closed', [
1485 | animate('500ms')
1486 | ]),
1487 | ```
1488 | 107. ### How to inject the dynamic script in angular?
1489 |
1490 | Using DomSanitizer we can inject the dynamic Html,Style,Script,Url.
1491 |
1492 | ```
1493 | import { Component, OnInit } from '@angular/core';
1494 | import { DomSanitizer } from '@angular/platform-browser';
1495 | @Component({
1496 | selector: 'my-app',
1497 | template: `
1498 |
1499 | `,
1500 | })
1501 | export class App {
1502 | constructor(protected sanitizer: DomSanitizer) {}
1503 | htmlSnippet: string = this.sanitizer.bypassSecurityTrustScript("");
1504 | }
1505 | ```
1506 | 108. ### What is a service worker and its role in Angular?
1507 | A service worker is a script that runs in the web browser and manages caching for an application. Starting from 5.0.0 version, Angular ships with a service worker implementation. Angular service worker is designed to optimize the end user experience of using an application over a slow or unreliable network connection, while also minimizing the risks of serving outdated content.
1508 | 109. ### What are the design goals of service workers?
1509 | Below are the list of design goals of Angular's service workers,
1510 | 1. It caches an application just like installing a native application
1511 | 2. A running application continues to run with the same version of all files without any incompatible files
1512 | 3. When you refresh the application, it loads the latest fully cached version
1513 | 4. When changes are published then it immediately updates in the background
1514 | 5. Service workers saves the bandwidth by downloading the resources only when they changed.
1515 | 110. ### What are the differences between AngularJS and Angular with respect to dependency injection?
1516 | Dependency injection is a common component in both AngularJS and Angular, but there are some key differences between the two frameworks in how it actually works.
1517 | | AngularJS | Angular |
1518 | |---- | ---------
1519 | | Dependency injection tokens are always strings | Tokens can have different types. They are often classes and sometimes can be strings. |
1520 | | There is exactly one injector even though it is a multi-module applications | There is a tree hierarchy of injectors, with a root injector and an additional injector for each component. |
1521 | 111. ### What is Angular Ivy?
1522 | Angular Ivy is a new rendering engine for Angular. You can choose to opt in a preview version of Ivy from Angular version 8.
1523 | 1. You can enable ivy in a new project by using the --enable-ivy flag with the ng new command
1524 | ```javascript
1525 | ng new ivy-demo-app --enable-ivy
1526 | ```
1527 | 2. You can add it to an existing project by adding `enableIvy` option in the `angularCompilerOptions` in your project's `tsconfig.app.json`.
1528 | ```javascript
1529 | {
1530 | "compilerOptions": { ... },
1531 | "angularCompilerOptions": {
1532 | "enableIvy": true
1533 | }
1534 | }
1535 | ```
1536 | 112. ### What are the features included in ivy preview?
1537 | You can expect below features with Ivy preview,
1538 | 1. Generated code that is easier to read and debug at runtime
1539 | 2. Faster re-build time
1540 | 3. Improved payload size
1541 | 4. Improved template type checking
1542 | 113. ### Can I use AOT compilation with Ivy?
1543 | Yes, it is a recommended configuration. Also, AOT compilation with Ivy is faster. So you need set the default build options(with in angular.json) for your project to always use AOT compilation.
1544 | ```javascript
1545 | {
1546 | "projects": {
1547 | "my-project": {
1548 | "architect": {
1549 | "build": {
1550 | "options": {
1551 | ...
1552 | "aot": true,
1553 | }
1554 | }
1555 | }
1556 | }
1557 | }
1558 | }
1559 | ```
1560 | 114. ### What is Angular Language Service?
1561 | The Angular Language Service is a way to get completions, errors, hints, and navigation inside your Angular templates whether they are external in an HTML file or embedded in annotations/decorators in a string. It has the ability to autodetect that you are opening an Angular file, reads your `tsconfig.json` file, finds all the templates you have in your application, and then provides all the language services.
1562 | 115. ### How do you install angular language service in the project?
1563 | You can install Angular Language Service in your project with the following npm command
1564 | ```javascript
1565 | npm install --save-dev @angular/language-service
1566 | ```
1567 | After that add the following to the "compilerOptions" section of your project's tsconfig.json
1568 | ```javascript
1569 | "plugins": [
1570 | {"name": "@angular/language-service"}
1571 | ]
1572 | ```
1573 | **Note:** The completion and diagnostic services works for .ts files only. You need to use custom plugins for supporting HTML files.
1574 | 116. ### Is there any editor support for Angular Language Service?
1575 | Yes, Angular Language Service is currently available for Visual Studio Code and WebStorm IDEs. You need to install angular language service using an extension and devDependency respectively. In sublime editor, you need to install typescript which has has a language service plugin model.
1576 | 117. ### Explain the features provided by Angular Language Service?
1577 | Basically there are 3 main features provided by Angular Language Service,
1578 |
1579 | 1. **Autocompletion:** Autocompletion can speed up your development time by providing you with contextual possibilities and hints as you type with in an interpolation and elements.
1580 |
1581 | 
1582 |
1583 | 2. **Error checking:** It can also warn you of mistakes in your code.
1584 |
1585 | 
1586 |
1587 | 3. **Navigation:** Navigation allows you to hover a component, directive, module and then click and press F12 to go directly to its definition.
1588 |
1589 | 
1590 | 118. ### How do you add web workers in your application?
1591 | You can add web worker anywhere in your application. For example, If the file that contains your expensive computation is `src/app/app.component.ts`, you can add a Web Worker using `ng generate web-worker app` command which will create `src/app/app.worker.ts` web worker file. This command will perform below actions,
1592 | 1. Configure your project to use Web Workers
1593 | 2. Adds app.worker.ts to receive messages
1594 | ```javascript
1595 | addEventListener('message', ({ data }) => {
1596 | const response = `worker response to ${data}`;
1597 | postMessage(response);
1598 | });
1599 | ```
1600 | 3. The component `app.component.ts` file updated with web worker file
1601 | ```javascript
1602 | if (typeof Worker !== 'undefined') {
1603 | // Create a new
1604 | const worker = new Worker('./app.worker', { type: 'module' });
1605 | worker.onmessage = ({ data }) => {
1606 | console.log('page got message: $\{data\}');
1607 | };
1608 | worker.postMessage('hello');
1609 | } else {
1610 | // Web Workers are not supported in this environment.
1611 | }
1612 | ```
1613 | **Note:** You may need to refactor your initial scaffolding web worker code for sending messages to and from.
1614 | 119. ### What are the limitations with web workers?
1615 | You need to remember two important things when using Web Workers in Angular projects,
1616 | 1. Some environments or platforms(like @angular/platform-server) used in Server-side Rendering, don't support Web Workers. In this case you need to provide a fallback mechanism to perform the computations to work in this environments.
1617 | 2. Running Angular in web worker using `@angular/platform-webworker` is not yet supported in Angular CLI.
1618 | 120. ### What is Angular CLI Builder?
1619 | In Angular8, the CLI Builder API is stable and available to developers who want to customize the `Angular CLI` by adding or modifying commands. For example, you could supply a builder to perform an entirely new task, or to change which third-party tool is used by an existing command.
1620 | 121. ### What is a builder?
1621 | A builder function ia a function that uses the `Architect API` to perform a complex process such as "build" or "test". The builder code is defined in an npm package. For example, BrowserBuilder runs a webpack build for a browser target and KarmaBuilder starts the Karma server and runs a webpack build for unit tests.
1622 | 122. ### How do you invoke a builder?
1623 | The Angular CLI command `ng run` is used to invoke a builder with a specific target configuration. The workspace configuration file, `angular.json`, contains default configurations for built-in builders.
1624 | 123. ### How do you create app shell in Angular?
1625 | An App shell is a way to render a portion of your application via a route at build time. This is useful to first paint of your application that appears quickly because the browser can render static HTML and CSS without the need to initialize JavaScript. You can achieve this using Angular CLI which generates an app shell for running server-side of your app.
1626 | ```javascript
1627 | ng generate appShell [options] (or)
1628 | ng g appShell [options]
1629 | ```
1630 | 124. ### What are the case types in Angular?
1631 | Angular uses capitalization conventions to distinguish the names of various types. Angular follows the list of the below case types.
1632 | 1. **camelCase :** Symbols, properties, methods, pipe names, non-component directive selectors, constants uses lowercase on the first letter of the item. For example, "selectedUser"
1633 | 2. **UpperCamelCase (or PascalCase):** Class names, including classes that define components, interfaces, NgModules, directives, and pipes uses uppercase on the first letter of the item.
1634 | 3. **dash-case (or "kebab-case"):** The descriptive part of file names, component selectors uses dashes between the words. For example, "app-user-list".
1635 | 4. **UPPER_UNDERSCORE_CASE:** All constants uses capital letters connected with underscores. For example, "NUMBER_OF_USERS".
1636 |
1637 | 125. ### What are the class decorators in Angular?
1638 | A class decorator is a decorator that appears immediately before a class definition, which declares the class to be of the given type, and provides metadata suitable to the type
1639 | The following list of decorators comes under class decorators,
1640 | 1. @Component()
1641 | 2. @Directive()
1642 | 3. @Pipe()
1643 | 4. @Injectable()
1644 | 5. @NgModule()
1645 |
--------------------------------------------------------------------------------
/images/architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ujwala123/https-github.com-sudheerj-angular-interview-questions/9a26559da2cbb078553383ca6d4077e4c5c200d5/images/architecture.png
--------------------------------------------------------------------------------
/images/createElement.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ujwala123/https-github.com-sudheerj-angular-interview-questions/9a26559da2cbb078553383ca6d4077e4c5c200d5/images/createElement.png
--------------------------------------------------------------------------------
/images/customElement.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ujwala123/https-github.com-sudheerj-angular-interview-questions/9a26559da2cbb078553383ca6d4077e4c5c200d5/images/customElement.png
--------------------------------------------------------------------------------
/images/language-completion.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ujwala123/https-github.com-sudheerj-angular-interview-questions/9a26559da2cbb078553383ca6d4077e4c5c200d5/images/language-completion.gif
--------------------------------------------------------------------------------
/images/language-error.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ujwala123/https-github.com-sudheerj-angular-interview-questions/9a26559da2cbb078553383ca6d4077e4c5c200d5/images/language-error.gif
--------------------------------------------------------------------------------
/images/language-navigation.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ujwala123/https-github.com-sudheerj-angular-interview-questions/9a26559da2cbb078553383ca6d4077e4c5c200d5/images/language-navigation.gif
--------------------------------------------------------------------------------
/images/lifecycle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Ujwala123/https-github.com-sudheerj-angular-interview-questions/9a26559da2cbb078553383ca6d4077e4c5c200d5/images/lifecycle.png
--------------------------------------------------------------------------------