├── .gitignore
├── images
├── lifecycle.png
├── architecture.png
├── createElement.png
└── customElement.png
├── .idea
├── vcs.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── modules.xml
├── misc.xml
└── angular-interview-questions.iml
├── LICENSE
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | *.idea
--------------------------------------------------------------------------------
/images/lifecycle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayatrahmani/angular-interview-questions-1/HEAD/images/lifecycle.png
--------------------------------------------------------------------------------
/images/architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayatrahmani/angular-interview-questions-1/HEAD/images/architecture.png
--------------------------------------------------------------------------------
/images/createElement.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayatrahmani/angular-interview-questions-1/HEAD/images/createElement.png
--------------------------------------------------------------------------------
/images/customElement.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayatrahmani/angular-interview-questions-1/HEAD/images/customElement.png
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | true
8 |
9 | false
10 | true
11 |
12 |
--------------------------------------------------------------------------------
/.idea/angular-interview-questions.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/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.
4 |
5 | ### Table of Contents
6 |
7 | | No. | Questions |
8 | |---- | ---------
9 | |1 | [What is Angular?](#what-is-angular) |
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 |
72 | 1. ### What is Angular Framework?
73 |
74 | 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.
75 |
76 | 2. ### What is the difference between AngularJS and Angular?
77 | Angular is a completely revived component-based framework in which an application is a tree of individual components.
78 |
79 | Some of the major difference in tabular form
80 |
81 | | AngularJS | Angular |
82 | |---- | ---------
83 | | It is based on MVC architecture | This is based on Service/Controller |
84 | | This uses use JavaScript to build the application| Introduced the typescript to write the application |
85 | | Based on controllers concept| This is a component based UI approach|
86 | | Not a mobile friendly framework| Developed considering mobile platform|
87 | | Difficulty in SEO friendly application development| Ease to create SEO friendly applications|
88 |
89 | 3. ### What is TypeScript?
90 | 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.
91 | You can install it globally as
92 | ```
93 | npm install -g typescript
94 | ```
95 | Let's see a simple example of TypeScript usage,
96 | ```typescript
97 | function greeter(person: string) {
98 | return "Hello, " + person;
99 | }
100 |
101 | let user = "Sudheer";
102 |
103 | document.body.innerHTML = greeter(user);
104 | ```
105 | The greeter method allows only string type as argument.
106 |
107 | 4. ### Write a pictorial diagram of Angular architecture?
108 | The main building blocks of an Angular application is shown in the below diagram
109 | 
110 |
111 | 5. ### What are the key components of Angular?
112 | Angular has the below key components,
113 | 1. **Component:** These are the basic building blocks of angular application to control HTML views.
114 | 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.
115 | 3. **Templates:** This represent the views of an Angular application.
116 | 4. **Services:** It is used to create components which can be shared across the entire application.
117 | 5. **Metadata:** This can be used to add more data to an Angular class.
118 |
119 | 6. ### What are directives?
120 | Directives add behaviour to an existing DOM element or an existing component instance.
121 | ```typescript
122 | import { Directive, ElementRef, Input } from '@angular/core';
123 |
124 | @Directive({ selector: '[myHighlight]' })
125 | export class HighlightDirective {
126 | constructor(el: ElementRef) {
127 | el.nativeElement.style.backgroundColor = 'yellow';
128 | }
129 | }
130 | ```
131 |
132 | Now this directive extends HTML element behavior with a yellow background as below
133 | ```html
134 |
Highlight me!
135 | ```
136 |
137 | 7. ### What are components?
138 | 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.
139 | Let's see a simple example of Angular component
140 | ```typescript
141 | import { Component } from '@angular/core';
142 |
143 | @Component ({
144 | selector: 'my-app',
145 | template: `
146 |
{{title}}
147 |
Learn Angular6 with examples
148 |
`,
149 | })
150 |
151 | export class AppComponent {
152 | title: string = 'Welcome to Angular world';
153 | }
154 | ```
155 |
156 | 8. ### What are the differences between Component and Directive?
157 | In a short note, A component(@component) is a directive-with-a-template.
158 |
159 | Some of the major differences are mentioned in a tabular form
160 |
161 | | Component | Directive |
162 | |---- | ---------
163 | | To register a component we use @Component meta-data annotation | To register directives we use @Directive meta-data annotation |
164 | | Components are typically used to create UI widgets| Directive is used to add behavior to an existing DOM element |
165 | | Component is used to break up the application into smaller components| Directive is use to design re-usable components|
166 | | Only one component can be present per DOM element | Many directives can be used per DOM element |
167 | | @View decorator or templateurl/template are mandatory | Directive doesn't use View|
168 |
169 | 9. ### What is a template?
170 | 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.
171 | **Using inline template with template syntax,**
172 | ```typescript
173 | import { Component } from '@angular/core';
174 |
175 | @Component ({
176 | selector: 'my-app',
177 | template: '
178 |
179 |
{{title}}
180 |
Learn Angular
181 |
182 | '
183 | })
184 |
185 | export class AppComponent {
186 | title: string = 'Hello World';
187 | }
188 | ```
189 | **Using separate template file such as app.component.html**
190 | ```typescript
191 | import { Component } from '@angular/core';
192 |
193 | @Component ({
194 | selector: 'my-app',
195 | templateUrl: 'app/app.component.html'
196 | })
197 |
198 | export class AppComponent {
199 | title: string = 'Hello World';
200 | }
201 | ```
202 |
203 | 10. ### What is a module?
204 |
205 | Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application.
206 | Lets take an example of **app.module.ts** root module declared with **@NgModule** decorator as below,
207 | ```typescript
208 | import { NgModule } from '@angular/core';
209 | import { BrowserModule } from '@angular/platform-browser';
210 | import { AppComponent } from './app.component';
211 |
212 | @NgModule ({
213 | imports: [ BrowserModule ],
214 | declarations: [ AppComponent ],
215 | bootstrap: [ AppComponent ]
216 | })
217 | export class AppModule { }
218 | ```
219 | The NgModule decorator has three options
220 | 1. The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
221 | 2. The declarations option is used to define components in the respective module
222 | 3. The bootstrap option tells Angular which Component to bootstrap in the application
223 |
224 | 11. ### What are lifecycle hooks available?
225 | Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application.
226 | The representation of lifecycle in pictorial representation as follows,
227 | 
228 |
229 |
230 | The description of each lifecycle method is as below,
231 | 1. **ngOnChanges:** When the value of a data bound property changes, then this method is called.
232 | 2. **ngOnInit:** This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
233 | 3. **ngDoCheck:** This is for the detection and to act on changes that Angular can't or won't detect on its own.
234 | 4. **ngAfterContentInit:** This is called in response after Angular projects external content into the component's view.
235 | 5. **ngAfterContentChecked:** This is called in response after Angular checks the content projected into the component.
236 | 6. **ngAfterViewInit:** This is called in response after Angular initializes the component's views and child views.
237 | 7. **ngAfterViewChecked:** This is called in response after Angular checks the component's views and child views.
238 | 8. **ngOnDestroy:** This is the cleanup phase just before Angular destroys the directive/component.
239 |
240 | 12. ### What is a data binding?
241 | 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.
242 | 1. **From the Component to the DOM:**
243 | **Interpolation:** {{ value }}: Adds the value of a property from the component
244 | ```html
245 |
Name: {{ user.name }}
246 |
Address: {{ user.address }}
247 | ```
248 | **Property binding:** [property]=”value”: The value is passed from the component to the specified property or simple HTML attribute
249 | ```html
250 |
251 | ```
252 | 2. **From the DOM to the Component:**
253 | **Event binding: (event)=”function”:** When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component
254 | ```html
255 |
256 | ```
257 | 3. **Two-way binding:**
258 | **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
259 | ```html
260 |
261 | ```
262 |
263 | 13. ### What is metadata?
264 | Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators
265 | 1. **Class decorators**, e.g. @Component and @NgModule
266 | ```typescript
267 | import { NgModule, Component } from '@angular/core';
268 |
269 | @Component({
270 | selector: 'my-component',
271 | template: '
Class decorator
',
272 | })
273 | export class MyComponent {
274 | constructor() {
275 | console.log('Hey I am a component!');
276 | }
277 | }
278 |
279 | @NgModule({
280 | imports: [],
281 | declarations: [],
282 | })
283 | export class MyModule {
284 | constructor() {
285 | console.log('Hey I am a module!');
286 | }
287 | }
288 | ```
289 | 2. **Property decorators** Used for properties inside classes, e.g. @Input and @Output
290 | ```typescript
291 | import { Component, Input } from '@angular/core';
292 |
293 | @Component({
294 | selector: 'my-component',
295 | template: '
'
310 | })
311 | export class MyComponent {
312 | @HostListener('click', ['$event'])
313 | onHostClick(event: Event) {
314 | // clicked, `event` available
315 | }
316 | }
317 | ```
318 | 4. **Parameter decorators** Used for parameters inside class constructors, e.g. @Inject
319 | ```typescript
320 | import { Component, Inject } from '@angular/core';
321 | import { MyService } from './my-service';
322 |
323 | @Component({
324 | selector: 'my-component',
325 | template: '
Parameter decorator
'
326 | })
327 | export class MyComponent {
328 | constructor(@Inject(MyService) myService) {
329 | console.log(myService); // MyService
330 | }
331 | }
332 | ```
333 |
334 | 14. ### What is angular CLI?
335 | Angular CLI(**Command Line Interface**) is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules.
336 | You need to install using below npm command,
337 | ```
338 | npm install @angular/cli@latest
339 | ```
340 | Below are the list of few commands, which will come handy while creating angular projects
341 | 1. **Creating New Project:** ng new
342 | 2. **Generating Components, Directives & Services:** ng generate/g
343 | The different types of commands would be,
344 | * ng generate class my-new-class: add a class to your application
345 | * ng generate component my-new-component: add a component to your application
346 | * ng generate directive my-new-directive: add a directive to your application
347 | * ng generate enum my-new-enum: add an enum to your application
348 | * ng generate module my-new-module: add a module to your application
349 | * ng generate pipe my-new-pipe: add a pipe to your application
350 | * ng generate service my-new-service: add a service to your application
351 | 3. **Running the Project:** ng serve
352 |
353 | 15. ### What is the difference between constructor and ngOnInit?
354 | 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.
355 | In order to use ngOnInit, you need to implement OnInit interface as below,
356 | ```typescript
357 | export class App implements OnInit{
358 | constructor(){
359 | //called first time before the ngOnInit()
360 | }
361 |
362 | ngOnInit(){
363 | //called after the constructor and called after the first ngOnChanges()
364 | }
365 | }
366 | ```
367 | 16. ### What is a service?
368 | 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.
369 | Let's create a repoService which can be used across components,
370 | ```typescript
371 | import { Injectable } from '@angular/core';
372 | import { Http } from '@angular/http';
373 |
374 | @Injectable() // The Injectable decorator is required for dependency injection to work
375 | export class RepoService{
376 | constructor(private http: Http){
377 | }
378 |
379 | fetchAll(){
380 | return this.http.get('https://api.github.com/repositories').map(res => res.json());
381 | }
382 | }
383 | ```
384 | The above service uses Http service as a dependency.
385 |
386 | 17. ### What is dependency injection in Angular?
387 | 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.
388 |
389 | 18. ### How is Dependency Hierarchy formed?
390 |
391 | 19. ### What is the purpose of async pipe?
392 | 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.
393 | Let's take a time observable which continuously updates the view for every 2 seconds with the current time.
394 | ```typescript
395 | @Component({
396 | selector: 'async-observable-pipe',
397 | template: `
observable|async:
398 | Time: {{ time | async }}
`
399 | })
400 | export class AsyncObservablePipeComponent {
401 | time = new Observable(observer =>
402 | setInterval(() => observer.next(new Date().toString()), 2000)
403 | );
404 | }
405 | ```
406 | 20. ### What is the option to choose between inline and external template file?
407 | 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.
408 | 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,
409 | ```
410 | ng generate component hero -it
411 | ```
412 | 21. ### What is the purpose of ngFor directive?
413 | We use Angular ngFor directive in the template to display each item in the list. For example, here we iterate over list of users,
414 | ```html
415 |
416 | {{ user }}
417 |
418 | ```
419 | The user variable in the ngFor double-quoted instruction is a **template input variable**
420 | 22. ### What is the purpose of ngIf directive?
421 | 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,
422 | ```html
423 |
18">You are not eligible for student pass!
424 | ```
425 | **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.
426 |
427 | 23. ### What happens if you use script tag inside template?
428 |
429 | Angular recognizes the value as unsafe and automatically sanitizes it, which removes the ** Syntax';
435 | }
436 | ```
437 |
438 | 24. ### What is interpolation?
439 |
440 | 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.
441 | Let's take an example,
442 | ```html
443 |
444 | {{title}}
445 |
446 |
447 | ```
448 | 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.
449 |
450 | 25. ### What are template expressions?
451 | 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".
452 | In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}},
453 | ```html
454 |
{{username}}, welcome to Angular
455 | ```
456 | The below javascript expressions are prohibited in template expression
457 | 1. assignments (=, +=, -=, ...)
458 | 2. new
459 | 3. chaining expressions with ; or ,
460 | 4. increment and decrement operators (++ and --)
461 | ----------------------------------
462 | 26. ### What are template statements?
463 | 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
464 | ```html
465 |
466 | ```
467 | In the above expression, editProfile is a template statement. The below JavaScript syntax expressions are not allowed.
468 | 1. new
469 | 2. increment and decrement operators, ++ and --
470 | 3. operator assignment, such as += and -=
471 | 4. the bitwise operators | and &
472 | 5. the template expression operators
473 | --------------------------------------
474 | 27. ### How do you categorize data binding types?
475 |
476 | Binding types can be grouped into three categories distinguished by the direction of data flow. They are listed as below,
477 | 1. From the source-to-view
478 | 2. From view-to-source
479 | 3. View-to-source-to-view
480 |
481 | The possible binding syntax can be tabularized as below,
482 |
483 | | Data direction | Syntax | Type |
484 | |---- | --------- | ---- |
485 | | From the source-to-view(One-way) | 1. {{expression}} 2. [target]="expression" 3. bind-target="expression" | Interpolation, Property, Attribute, Class, Style|
486 | | From view-to-source(One-way) | 1. (target)="statement" 2. on-target="statement" | Event |
487 | | View-to-source-to-view(Two-way)| 1. [(target)]="expression" 2. bindon-target="expression"| Two-way |
488 |
489 | 28. ### What are pipes?
490 | 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.
491 | ```javascript
492 | import { Component } from '@angular/core';
493 |
494 | @Component({
495 | selector: 'app-birthday',
496 | template: `
Birthday is {{ birthday | date }}
`
497 | })
498 | export class BirthdayComponent {
499 | birthday = new Date(1987, 6, 18); // June 18, 1987
500 | }
501 | ```
502 | 29. ### What is a parameterized pipe?
503 | 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):
504 | ```javascript
505 | import { Component } from '@angular/core';
506 |
507 | @Component({
508 | selector: 'app-birthday',
509 | template: `
Birthday is {{ birthday | date | 'dd/mm/yyyy'}}
` // 18/06/1987
510 | })
511 | export class BirthdayComponent {
512 | birthday = new Date(1987, 6, 18);
513 | }
514 | ```
515 | **Note:** The parameter value can be any valid template expression, such as a string literal or a component property.
516 | 30. ### How do you chain pipes?
517 | 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
518 | ```javascript
519 | import { Component } from '@angular/core';
520 |
521 | @Component({
522 | selector: 'app-birthday',
523 | template: `
Birthday is {{ birthday | date:'fullDate' | uppercase}}
` // THURSDAY, JUNE 18, 1987
524 | })
525 | export class BirthdayComponent {
526 | birthday = new Date(1987, 6, 18);
527 | }
528 |
529 | ```
530 | 31. ### What is a custom pipe?
531 | Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,
532 | 1. A pipe is a class decorated with pipe metadata **@Pipe** decorator, which you import from the core Angular library
533 | For example,
534 | ```javascript
535 | @Pipe({name: 'myCustomPipe'})
536 | ```
537 | 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.
538 | The structure of pipeTransform would be as below,
539 | ```javascript
540 | interface PipeTransform {
541 | transform(value: any, ...args: any[]): any
542 | }
543 | ```
544 | 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.
545 | ```javascript
546 | template: `{{someInputValue | myCustomPipe: someOtherValue}}`
547 | ```
548 | 32. ### Give an example of custom pipe?
549 | 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,
550 | ```javascript
551 | import { Pipe, PipeTransform } from '@angular/core';
552 |
553 | @Pipe({name: 'customFileSizePipe'})
554 | export class FileSizePipe implements PipeTransform {
555 | transform(size: number, extension: string = 'MB'): string {
556 | return (size / (1024 * 1024)).toFixed(2) + extension;
557 | }
558 | }
559 | ```
560 | Now you can use the above pipe in template expression as below,
561 | ```javascript
562 | template: `
563 |
Find the size of a file
564 |
Size: {{288966 | customFileSizePipe: 'GB'}}
565 | `
566 | ```
567 | 33. ### What is the difference between pure and impure pipe?
568 | 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.
569 | 34. ### What is a bootstrapping module?
570 | 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,
571 | ```javascript
572 | /* JavaScript imports */
573 | import { BrowserModule } from '@angular/platform-browser';
574 | import { NgModule } from '@angular/core';
575 | import { FormsModule } from '@angular/forms';
576 | import { HttpClientModule } from '@angular/common/http';
577 |
578 | import { AppComponent } from './app.component';
579 |
580 | /* the AppModule class with the @NgModule decorator */
581 | @NgModule({
582 | declarations: [
583 | AppComponent
584 | ],
585 | imports: [
586 | BrowserModule,
587 | FormsModule,
588 | HttpClientModule
589 | ],
590 | providers: [],
591 | bootstrap: [AppComponent]
592 | })
593 | export class AppModule { }
594 | ```
595 | 35. ### What are observables?
596 | 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.
597 | 36. ### What is HttpClient and its benefits?
598 | 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.
599 | You can import in your root module as below,
600 | ```javascript
601 | import { HttpClientModule } from '@angular/common/http';
602 | ```
603 |
604 | The major advantages of HttpClient can be listed as below,
605 | 1. Contains testability features
606 | 2. Provides typed request and response objects
607 | 3. Intercept request and response
608 | 4. Supports Observalbe APIs
609 | 5. Supports streamlined error handling
610 |
611 | 37. ### Explain on how to use HttpClient with an example?
612 | Below are the steps need to be followed for the usage of HttpClient.
613 | 1. Import HttpClient into root module:
614 | ```javascript
615 | import { HttpClientModule } from '@angular/common/http';
616 | @NgModule({
617 | imports: [
618 | BrowserModule,
619 | // import HttpClientModule after BrowserModule.
620 | HttpClientModule,
621 | ],
622 | ......
623 | })
624 | export class AppModule {}
625 | ```
626 | 2. Inject the HttpClient into the application:
627 | Let's create a userProfileService(userprofile.service.ts) as an example. It also defines get method of HttpClient
628 | ```javascript
629 | import { Injectable } from '@angular/core';
630 | import { HttpClient } from '@angular/common/http';
631 |
632 | const userProfileUrl: string = 'assets/data/profile.json';
633 |
634 | @Injectable()
635 | export class UserProfileService {
636 | constructor(private http: HttpClient) { }
637 | }
638 |
639 | getUserProfile() {
640 | return this.http.get(this.userProfileUrl);
641 | }
642 | ```
643 | 3. Create a component for subscribing service:
644 | Let's create a component called UserProfileComponent(userprofile.component.ts) which inject UserProfileService and invokes the service method,
645 | ```javascript
646 | fetchUserProfile() {
647 | this.userProfileService.getUserProfile()
648 | .subscribe((data: User) => this.user = {
649 | id: data['userId'],
650 | name: data['firstName'],
651 | city: data['city']
652 | });
653 | }
654 | ```
655 | Since the above service method returns an Observable which needs to be subscribed in the component.
656 | 38. ### How can you read full response?
657 | 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,
658 | ```javascript
659 | getUserResponse(): Observable> {
660 | return this.http.get(
661 | this.userUrl, { observe: 'response' });
662 | }
663 | ```
664 | Now HttpClient.get() method returns an Observable of typed HttpResponse rather than just the JSON data.
665 | 39. ### How do you perform Error handling?
666 | 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.
667 | Let's see how it can be handled in the component with an example,
668 | ```javascript
669 | fetchUser() {
670 | this.userService.getProfile()
671 | .subscribe(
672 | (data: User) => this.userProfile = { ...data }, // success path
673 | error => this.error = error // error path
674 | );
675 | }
676 | ```
677 | It is always a good idea to give the user some meaningful feedback instead of displaying the raw error object returned from HttpClient.
678 | 40. ### What is RxJS?
679 | 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.
680 | For example, you can import observables and operators for using HttpClient as below,
681 | ```javascript
682 | import { Observable, throwError } from 'rxjs';
683 | import { catchError, retry } from 'rxjs/operators';
684 | ```
685 | 41. ### What is subscribing?
686 | 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.
687 | Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.
688 | ```javascript
689 | Creates an observable sequence of 5 integers, starting from 1
690 | const source = range(1, 5);
691 |
692 | // Create observer object
693 | const myObserver = {
694 | next: x => console.log('Observer got a next value: ' + x),
695 | error: err => console.error('Observer got an error: ' + err),
696 | complete: () => console.log('Observer got a complete notification'),
697 | };
698 |
699 | // Execute with the observer object and Prints out each item
700 | myObservable.subscribe(myObserver);
701 | // => Observer got a next value: 1
702 | // => Observer got a next value: 2
703 | // => Observer got a next value: 3
704 | // => Observer got a next value: 4
705 | // => Observer got a next value: 5
706 | // => Observer got a complete notification
707 | ```
708 | 42. ### What is an observable?
709 | 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.
710 | The observables are created using new keyword. Let see the simple example of observable,
711 | ```javascript
712 | import { Observable } from 'rxjs';
713 |
714 | const observable = new Observable(observer => {
715 | setTimeout(() => {
716 | observer.next('Hello from a Observable!');
717 | }, 2000);
718 | });
719 | ```
720 |
721 | 43. ### What is an observer?
722 | Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure,
723 | ```javascript
724 | interface Observer {
725 | closed?: boolean;
726 | next: (value: T) => void;
727 | error: (err: any) => void;
728 | complete: () => void;
729 | }
730 | ```
731 | A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below,
732 | ```javascript
733 | myObservable.subscribe(myObserver);
734 | ```
735 | **Note:** If you don't supply a handler for a notification type, the observer ignores notifications of that type.
736 | 44. ### What is the difference between promise and observable?
737 | Below are the list of differences between promise and observable,
738 |
739 | | Observable | Promise |
740 | |---- | --------- |
741 | | Declarative: Computation does not start until subscription so that they can be run whenever you need the result | Execute immediately on creation|
742 | | Provide multiple values over time | Provide only one |
743 | | Subscribe method is used for error handling which makes centralized and predictable error handling| Push errors to the child promises |
744 | | Provides chaining and subscription to handle complex applications | Uses only .then() clause |
745 |
746 | 45. ### What is multicasting?
747 | Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let's demonstrate the multi-casting feature,
748 | ```javascript
749 | var source = Rx.Observable.from([1, 2, 3]);
750 | var subject = new Rx.Subject();
751 | var multicasted = source.multicast(subject);
752 |
753 | // These are, under the hood, `subject.subscribe({...})`:
754 | multicasted.subscribe({
755 | next: (v) => console.log('observerA: ' + v)
756 | });
757 | multicasted.subscribe({
758 | next: (v) => console.log('observerB: ' + v)
759 | });
760 |
761 | // This is, under the hood, `s
762 | ```
763 | 46. ### How do you perform error handling in observables?
764 | 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,
765 | ```javascript
766 | myObservable.subscribe({
767 | next(num) { console.log('Next num: ' + num)},
768 | error(err) { console.log('Received an errror: ' + err)}
769 | });
770 | ```
771 | 47. ### What is the short hand notation for subscribe method?
772 | 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,
773 | ```javascript
774 | myObservable.subscribe(
775 | x => console.log('Observer got a next value: ' + x),
776 | err => console.error('Observer got an error: ' + err),
777 | () => console.log('Observer got a complete notification')
778 | );
779 | ```
780 | 48. ### What are the utility functions provided by RxJS?
781 | The RxJS library also provides below utility functions for creating and working with observables.
782 | 1. Converting existing code for async operations into observables
783 | 2. Iterating through the values in a stream
784 | 3. Mapping values to different types
785 | 4. Filtering streams
786 | 5. Composing multiple streams
787 | 49. ### What are observable creation functions?
788 | 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,
789 | 1. Create an observable from a promise
790 | ```javascript
791 | import { from } from 'rxjs'; // from function
792 | const data = from(fetch('/api/endpoint')); //Created from Promise
793 | data.subscribe({
794 | next(response) { console.log(response); },
795 | error(err) { console.error('Error: ' + err); },
796 | complete() { console.log('Completed'); }
797 | });
798 | ```
799 | 2. Create an observable that creates an AJAX request
800 | ```javascript
801 | import { ajax } from 'rxjs/ajax'; // ajax function
802 | const apiData = ajax('/api/data'); // Created from AJAX request
803 | // Subscribe to create the request
804 | apiData.subscribe(res => console.log(res.status, res.response));
805 | ```
806 | 3. Create an observable from a counter
807 | ```javascript
808 | import { interval } from 'rxjs'; // interval function
809 | const secondsCounter = interval(1000); // Created from Counter value
810 | secondsCounter.subscribe(n =>
811 | console.log(`Counter value: ${n}`));
812 | ```
813 | 4. Create an observable from an event
814 | ```javascript
815 | import { fromEvent } from 'rxjs';
816 | const el = document.getElementById('custom-element');
817 | const mouseMoves = fromEvent(el, 'mousemove');
818 | const subscription = mouseMoves.subscribe((e: MouseEvent) => {
819 | console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
820 | });
821 | ```
822 | 50. ### What will happen if you do not supply handler for observer?
823 | 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.
824 | 51. ### What are angular elements?
825 | 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`.
826 | 52. ### What is the browser support of Angular Elements?
827 | 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.
828 |
829 | | Browser | Angular Element Support |
830 | |---- | --------- |
831 | | Chrome | Natively supported|
832 | | Opera | Natively supported |
833 | | Safari| Natively supported |
834 | | Firefox | Natively supported from 63 version onwards. You need to enable dom.webcomponents.enabled and dom.webcomponents.customelements.enabled in older browsers |
835 | | Edge| Currently it is in progress|
836 | 53. ### What are custom elements?
837 | 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.
838 | 54. ### Do I need to bootstrap custom elements?
839 | 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.
840 | 55. ### Explain how custom elements works internally?
841 | Below are the steps in an order about custom elements functionality,
842 | 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.
843 | 2. **App adds custom element to DOM:** Add custom element just like a built-in HTML element directly into the DOM.
844 | 3. **Browser instantiate component based class:** Browser creates an instance of the registered class and adds it to the DOM.
845 | 4. **Instance provides content with data binding and change detection:** The content with in template is rendered using the component and DOM data.
846 | The flow chart of the custom elements functionality would be as follows,
847 | 
848 | 56. ### How to transfer components to custom elements?
849 | Transforming components to custom elements involves **two** major steps,
850 | 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.
851 | 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.
852 | The detailed structure would be as follows,
853 | 
854 | 57. ### What are the mapping rules between Angular component and custom element?
855 | The Component properties and logic maps directly into HTML attributes and the browser's event system. Let us describe them in two steps,
856 | 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`.
857 | 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".
858 | 58. ### How do you define typings for custom elements?
859 | 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,
860 | The simple container with input property would be as below,
861 | ```javascript
862 | @Component(...)
863 | class MyContainer {
864 | @Input() message: string;
865 | }
866 | ```
867 | After applying types typescript validates input value and their types,
868 | ```javascirpt
869 | const container = document.createElement('my-container') as NgElement & WithProperties<{message: string}>;
870 | container.message = 'Welcome to Angular elements!';
871 | container.message = true; // <-- ERROR: TypeScript knows this should be a string.
872 | container.greet = 'News'; // <-- ERROR: TypeScript knows there is no `greet` property on `container`.
873 | ```
874 | 59. ### What are dynamic components?
875 | 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.
876 | 60. ### What are the various kinds of directives?
877 | There are mainly three kinds of directives.
878 | 1. **Components** — These are directives with a template.
879 | 2. **Structural directives** — These directives change the DOM layout by adding and removing DOM elements.
880 | 3. **Attribute directives** — These directives change the appearance or behavior of an element, component, or another directive.
881 | 61. ### How do you create directives using CLI?
882 | 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.
883 | 62. ### Give an example for attribute directives?
884 | Let's take simple highlighter behavior as a example directive for DOM element. You can create and apply the attribute directive using below steps,
885 | 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 ,
886 | ```javascript
887 | import { Directive, ElementRef } from '@angular/core';
888 |
889 | @Directive({
890 | selector: '[appHighlight]'
891 | })
892 | export class HighlightDirective {
893 | constructor(el: ElementRef) {
894 | el.nativeElement.style.backgroundColor = 'red';
895 | }
896 | }
897 | ```
898 | 2. Apply the attribute directive as an attribute to the host element(for example,
)
899 | ```javascript
900 |
Highlight me!
901 | ```
902 | 3. Run the application to see the highlight behavior on paragraph element
903 | ```javascript
904 | ng serve
905 | ```
--------------------------------------------------------------------------------