├── .gitignore ├── angularFeelings.md ├── lifecycle-hooks.md ├── CONTRIBUTING.md ├── animation.md ├── typescript.md ├── pipes.md ├── architecture.md ├── testing.md ├── template.md ├── style.md ├── structural-directives.md ├── observables-rxjs.md ├── JavaScript.md ├── services.md ├── components.md ├── router.md ├── api.md ├── ngModule.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | answers/ 2 | -------------------------------------------------------------------------------- /angularFeelings.md: -------------------------------------------------------------------------------- 1 | //Share what you don't like about angular here. Thanks! 2 | -------------------------------------------------------------------------------- /lifecycle-hooks.md: -------------------------------------------------------------------------------- 1 | What would you consider a thing you should be careful doing on ngOnInit()? 2 | * https://angular.io/docs/ts/latest/guide/router.html#!#route-config (OBSERVABLE PARAMS AND COMPONENT RE-USE) 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Submitting a Pull Request(PR) 2 | 3 | * Make your changes in a new git branch: 4 | 5 | ```shell 6 | git checkout -b my-fix-branch master 7 | ``` 8 | * Add yourself and a link to your github profile to the contributors list on the main [README](https://github.com/Yonet/Angular-Interview-Questions#contributors) 9 | 10 | * Commit your changes using a descriptive commit message. 11 | 12 | * Send a pull request to master branch. 13 | -------------------------------------------------------------------------------- /animation.md: -------------------------------------------------------------------------------- 1 | * How do you transition between two states: 2 | 3 | ```ts 4 | animations: [ 5 | trigger('heroState', [ 6 | state('inactive', style({ 7 | backgroundColor: '#eee', 8 | transform: 'scale(1)' 9 | })), 10 | state('active', style({ 11 | backgroundColor: '#cfd8dc', 12 | transform: 'scale(1.1)' 13 | })), 14 | transition('inactive => active', animate('100ms ease-in')), 15 | transition('active => inactive', animate('100ms ease-out')) 16 | ]) 17 | ] 18 | ``` 19 | 20 | * How do you define a wildcard state? 21 | 22 | ```ts 23 | * => * 24 | * => active 25 | ``` 26 | -------------------------------------------------------------------------------- /typescript.md: -------------------------------------------------------------------------------- 1 | * Why do you need type definitions? 2 | 3 | 4 | * How would you define a custom type? 5 | 6 | 7 | * What is the difference between an Interface and a Class? 8 | 9 | 10 | * First line below gives compile error, second line doesn't. Why? 11 | 12 | 13 | * What are Discriminated union types? 14 | 15 | https://basarat.gitbooks.io/typescript/content/docs/types/discriminated-unions.html 16 | https://github.com/Microsoft/TypeScript/pull/9163 17 | 18 | * How do you define Object of Objects type in typescript? 19 | 20 | * How can you capture the 'type' the user provides (e.g. number), so that we can use that information later. 21 | 22 | ```ts 23 | function identity(arg: T): T { 24 | return arg; 25 | } 26 | ``` 27 | [Read more...](https://www.typescriptlang.org/docs/handbook/generics.html) 28 | -------------------------------------------------------------------------------- /pipes.md: -------------------------------------------------------------------------------- 1 | * What is a pure pipe? 2 | * What is an async pipe? 3 | * What kind of data can be used with async pipe? 4 | * How do you create a custom pipe? 5 | 6 | * How does async pipe prevents memory leeks? 7 | 8 | Async pipe knows about the lifespan of the component and unscubscribes from the observable if necessary. 9 | 10 | * What is the difference between pure and impure pipes? 11 | 12 | `Pure Pipes:` 13 | 14 | * Input parameters value determine the output so if input parameters don’t change the output doesn’t change. 15 | * Can be shared across many usages without affecting the output result. 16 | * Pure pipes are pure functions that are easy to test. 17 | 18 | `Impure Pipes:` 19 | 20 | * Cannot use the input value to determine if the output will change. 21 | * Cannot be shared because the internal state can be affected from outside. 22 | -------------------------------------------------------------------------------- /architecture.md: -------------------------------------------------------------------------------- 1 | * What is a good use case for ngrx/store? 2 | 3 | Here is a great talk that goes into detail of the problems ngrx solving to manage state in applications by [Victor Savkin](https://twitter.com/victorsavkin?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor): https://www.youtube.com/watch?v=brCGZ8Lk-HY&t=1245s 4 | 5 | * Can you talk about a bug related to a race condition, how to solve it and how to test it? 6 | 7 | You can find the answer of this question in detail in this article: https://blog.nrwl.io/rxjs-advanced-techniques-testing-race-conditions-using-rxjs-marbles-53e7e789fba5 8 | 9 | * What is the difference between a smart/container component and dumb/presentational component? What is a good use case example? What are the advantages? 10 | 11 | You can find the answer of this question in the great article from [Dan Abramov](https://twitter.com/dan_abramov?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor): https://goo.gl/GnoSAa 12 | -------------------------------------------------------------------------------- /testing.md: -------------------------------------------------------------------------------- 1 | #### Testing Questions: 2 | 3 | * What are some of the different tests types you can write? 4 | 5 | Isolated, shallow, integration, e2e. 6 | 7 | * How do you mock a service to inject in an integration test? 8 | * How do you mock a module in an integration test? 9 | * How do you test a component that has a dependency to an async service? 10 | * What is the difference between 'async()' and 'fakeAsync()'? 11 | 12 | async(): 13 | 14 | Wraps a test function in an asynchronous test zone. 15 | The test will automatically complete when all asynchronous calls within this zone are done. 16 | Can be used to wrap an inject call. 17 | 18 | [Read more...](https://next.angular.io/api/core/testing/async) 19 | 20 | fakeAsync(): 21 | Wraps a function to be executed in the fakeAsync zone: 22 | + microtasks are manually executed by calling flushMicrotasks(), 23 | + timers are synchronous, tick() simulates the asynchronous passage of time. 24 | 25 | [Read more...](https://next.angular.io/api/core/testing/fakeAsync) 26 | -------------------------------------------------------------------------------- /template.md: -------------------------------------------------------------------------------- 1 | * How can you add an active class to a selected element in a list component? 2 | * What is a template variable. How would you use it? 3 | * What is the difference of using a property binding verses a function binding on a template? 4 | * What happens if you subscribe to a data source multiple times with async pipe? 5 | * what is the difference between ng-content, ng-container and ng- template? 6 | * When you create a data-binding in Angular, are you working with attributes or properties? What is the difference anyway? 7 | 8 | In the world of Angular, the only role of attributes is to initialize element and directive state. When you write a data binding, you're dealing exclusively with properties and events of the target object. 9 | HTML attributes effectively disappear. [Read more](https://next.angular.io/guide/template-syntax#html-attribute-vs-dom-property) 10 | 11 | * When can you omit the brackets in template binding? 12 | 13 | You should omit the brackets when all of the following are true: 14 | 15 | The target property accepts a string value. 16 | The string is a fixed value that you can bake into the template. 17 | This initial value never changes. 18 | 19 | [Read more](https://next.angular.io/guide/template-syntax#one-time-string-initialization) 20 | -------------------------------------------------------------------------------- /style.md: -------------------------------------------------------------------------------- 1 | * How would you select a custom component to style it. 2 | * What pseudo-class selector targets styles in the element that hosts the component? 3 | * How would you select all the child components' elements? 4 | * How would you select a css class in any ancestor of the component host element, all the way up to the document root? 5 | * What selector force a style down through the child component tree into all the child component views? 6 | 7 | We can use the /deep/ selector to force a style down through the child component tree into all the child component views. The /deep/ selector works to any depth of nested components, and it applies both to the view children and the content children of the component. 8 | 9 | * What does :host-context() pseudo-class selector targets? 10 | 11 | It works just like the function form of :host(). It looks for a CSS class in any ancestor of the component host element, all the way up to the document root. It's useful when combined with another selector. 12 | 13 | * What does the following css do? 14 | 15 | ```css 16 | :host-context(.theme-light) h2 { 17 | background-color: red; 18 | } 19 | ``` 20 | 21 | Applies a background-color style to all

elements inside the component, only if some ancestor element has the CSS class theme-light. 22 | -------------------------------------------------------------------------------- /structural-directives.md: -------------------------------------------------------------------------------- 1 | 2 | * What is a structural directive? 3 | 4 | 5 | Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements. 6 | 7 | 8 | 9 | * How do you identify a structural directive in html? 10 | 11 | 12 | By the '*' before the directive name as in `

` 13 | 14 | 15 | * When creating your own structural directives, how would you decide on hiding or removing an element? What would be the advantages or disadvantages of choosing one method rather than the other? 16 | 17 | 18 | The difference between hiding and removing doesn't matter for a simple paragraph. It does matter when the host element is attached to a resource intensive component. Such a component's behavior continues even when hidden. The component stays attached to its DOM element. It keeps listening to events. Angular keeps checking for changes that could affect data bindings. Whatever the component was doing, it keeps doing. 19 | 20 | Although invisible, the component—and all of its descendant components—tie up resources. The performance and memory burden can be substantial, responsiveness can degrade, and the user sees nothing. 21 | 22 | On the positive side, showing the element again is quick. The component's previous state is preserved and ready to display. The component doesn't re-initialize—an operation that could be expensive. So hiding and showing is sometimes the right thing to do. 23 | 24 | But in the absence of a compelling reason to keep them around, your preference should be to remove DOM elements that the user can't see and recover the unused resources with a structural directive like NgIf . 25 | -------------------------------------------------------------------------------- /observables-rxjs.md: -------------------------------------------------------------------------------- 1 | * What is the difference between an observable and a promise? 2 | 3 | Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. However, there are important differences between the two: 4 | - Observables can define both the setup and teardown aspects of asynchronous behavior. 5 | - Observables are cancellable. 6 | - Moreover, Observables can be retried using one of the retry operators provided by the API, such as retry and retryWhen. On the other hand, Promises require the caller to have access to the original function that returned the promise in order to have a retry capability. 7 | 8 | 9 | 10 | * What is the difference between `scan()` vs `reduce()` ? 11 | 12 | - Scan will show all values emitted on source observable. 13 | - Reduce will show only the final value emitted on source observable. 14 | 15 | ```js 16 | var obsScan = Observable.from([1,2,3,4,5,6]); 17 | var count1 = obsScan.scan((acc, one) => acc + one, 0); 18 | count1.subscribe(x => { 19 | console.log('scan shows incremental total', x); 20 | }); 21 | 22 | var obsReduce = Observable.from([1,2,3,4,5,6]); 23 | var count2 = obsReduce.reduce((acc, one) => acc + one, 0); 24 | count2.subscribe(x => { 25 | console.log('reduce shows only total', x); 26 | }); 27 | ``` 28 | 29 | Output : 30 | 31 |

32 |     scan shows incremental total 1
33 |     scan shows incremental total 3
34 |     scan shows incremental total 6
35 |     scan shows incremental total 10
36 |     scan shows incremental total 15
37 |     scan shows incremental total 21
38 |     reduce shows only total 21
39 |     
40 | 41 | Video example : 42 | 43 | drawing 44 | -------------------------------------------------------------------------------- /JavaScript.md: -------------------------------------------------------------------------------- 1 | * Explain the difference between var, let and const key words. 2 | * Could you make sure a const value is garbage collected? 3 | Yes, but... 4 | Assigning an object or array as a constant means that value will not be able to be garbage collected until that constant’s lexical scope goes away, as the reference to the value can never be unset. 5 | That may be desirable, but be careful if it’s not your intent! 6 | [Read more...](https://books.google.com/books?id=iOc6CwAAQBAJ&pg=PT24&lpg=PT24&dq=keyle+simpson+Assigning+an+object+or+array+as+a+constant+means+that+value+will+not+be+able+to+be+garbage+collected+until+that+constant%E2%80%99s+lexical+scope+goes+away,&source=bl&ots=7v7iLPetjx&sig=t8flr1cB-DlnFaBMhlCcewpW2bs&hl=en&sa=X&ved=0ahUKEwjZ-czuteDbAhWaHTQIHeGlAhgQ6AEINDAC#v=onepage&q=keyle%20simpson%20Assigning%20an%20object%20or%20array%20as%20a%20constant%20means%20that%20value%20will%20not%20be%20able%20to%20be%20garbage%20collected%20until%20that%20constant%E2%80%99s%20lexical%20scope%20goes%20away%2C&f=false) 7 | * Explain Object.assign and possible use cases. 8 | * Explain Object.freeze and possible use cases. 9 | * Explain the code below. How many times the createVal function is called? 10 | 11 | ```ts 12 | function createVal(){ 13 | return Math.random(); 14 | }; 15 | 16 | function fun( val = createVal()){ 17 | // Do something with val... 18 | } 19 | 20 | fun(); 21 | fun(5); 22 | 23 | ``` 24 | * What is the spread operator doing in this function call? Seriously! 25 | 26 | ``` 27 | doStuff(...args); 28 | ``` 29 | 30 | With the spread operator we can avoid apply all together and simply call the function with the spread operator. [Read more...](https://davidwalsh.name/spread-operator). 31 | Note: although there it looks simpler, I think this is less readable at the moment since more developers are familiar with apply. 32 | 33 | 34 | * What is [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)? 35 | * Explain why the below stand-alone syntax is not valid? 36 | 37 | ```js 38 | {a, b} = {a: 1, b: 2} 39 | ``` 40 | 41 | {a, b} on the left-hand side is considered a block and not an object literal. 42 | 43 | However, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2} 44 | 45 | Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line. 46 | -------------------------------------------------------------------------------- /services.md: -------------------------------------------------------------------------------- 1 | #### What is the use case of services? 2 | 3 | The main use case of Services is to move duplicated code into a single location, acting like a Singleton. It encourages DRY (Don't Repeat Yourself), which is a principle in Software Engineering, aimed at reducing repitition of information or code in a multi-layered architecture. 4 | 5 | Services can serve as a method of interaction between an application and a data store. It also can provide communication channels between directives, as well as any other business logic access. 6 | 7 | #### How are the services injected to your application? 8 | 9 | There are two ways to inject a service into your application: 10 | 11 | - Per Application: Provides the service at an application level 12 | - Per Component: Provides the service at a component level (and all child components) 13 | 14 | Providing a service at an application level or a higher level creates a single instance of that service and shares it with all sub directives. This is useful in the case of sharing properties or state between service holders. 15 | 16 | Providing a service for every different component would create an instance for each of the components with separate resources. 17 | 18 | Injecting a service can be done by importing the service and specifying it in the `NgModule`'s metadata array preperty `providers`, and inject it into the directive using it via the constructor. To inject a service into another service, annotate the target service class with `@Injectable`. 19 | 20 | ```ts 21 | //annotation used for services injecting other services 22 | @Injectable() 23 | export class MessageService { 24 | //injected service 25 | constructor(private errorService: ErrorService){} 26 | } 27 | ``` 28 | 29 | #### How do you unit test a service with a dependency? 30 | [insert answer] 31 | 32 | #### Why is it a bad idea to create a new service in a component like the one below? 33 | 34 | ```ts 35 | let service = new DataService(); 36 | ``` 37 | 38 | That's a bad idea for several reasons including: 39 | 40 | Our component has to know how to create a DataService. If we ever change the DataService constructor, we'll have to find every place we create the service and fix it. Running around patching code is error prone and adds to the test burden. 41 | 42 | We create a new service each time we use new. What if the service should cache data and share that cache with others? We couldn't do that. 43 | 44 | We're locking the component into a specific implementation of the DataService. It will be hard to switch implementations for different scenarios. Can we operate offline? Will we need different mocked versions under test? Not easy. 45 | -------------------------------------------------------------------------------- /components.md: -------------------------------------------------------------------------------- 1 | ## Components 2 | 3 | #### What is the minimum definition of a component? 4 | 5 | import { Component } from '@angular/core'; 6 | 7 | @Component({ 8 | templateUrl: './minimum.component.html' // or 9 | template: '' 10 | }) 11 | export class MinimumComponent {} 12 | 13 | Note that: 14 | 15 | * constructor is not requred, it is auto generated 16 | * selector is not required, component can be accessed via router by class name 17 | * template is required (either template or templateUrl) 18 | 19 | #### What is the difference between a component and a directive? 20 | 21 | There are three kinds of directives in Angular: 22 | 23 | * components - directive with a template 24 | * structural directives - changes DOM layout by adding and removing elements i.e. *ngFor 25 | * attribute directives - changes appearance or behaviour of an element, component or another directive 26 | (ngStyle for example) 27 | 28 | so precisely: 29 | 30 | * component uses @Component decorator, directive uses @Directive decorator 31 | * component has template, directive has not 32 | 33 | #### How do components comunicate with each other? 34 | 35 | Types of communication: 36 | 37 | * parent/child communication using @Input decorator and @Output decorator with EventEmitter 38 | * communication using services and Angular dependency injection system 39 | * communication via store (redux) which also uses Angular DI 40 | 41 | #### How to create two way data binding in Angular? 42 | 43 | To set up two way data binding one must use both () and [], so: 44 | 45 | * `` is the way to go 46 | * `` is also valid equivalent 47 | * `` this a special case for form control binding 48 | 49 | #### How would you create a component to display error messages throughout your application? 50 | 51 | There are many possible ways, but let's say we want toastie to display an error. We do: 52 | 53 | 1. Create ErrorService which we inject everywhere from where we want to propagate error to display. 54 | 2. Create ToastieContainerComponent, inject service here and subscribe to errors. This component propagates 55 | values to child componentand manages its lifecycle. 56 | 3. Create presentational component ToastieComponent which displays toastie to user and gets values via @Input 57 | from component. 58 | 4. Use ToastieContainerComponents somewhere in your app preferably in AppComponent. 59 | 60 | #### What does lean component mean to you? 61 | 62 | A lean component is a component which solely purpose is to display data to user. This means such component 63 | delegates data fetching, bussiness logic, input validation etc. to other classes like models, services, 64 | redux effects/actions etc. Lean component follows single responsibility principle. 65 | -------------------------------------------------------------------------------- /router.md: -------------------------------------------------------------------------------- 1 | #### What is the diffrence between RouterModule.forRoot() vs RouterModule.forChild()? Why is it important? 2 | 3 | * forRoot creates a module that contains all the directives, the given routes, and the router service itself. 4 | * forChild creates a module that contains all the directives and the given routes, but does not include the router service. 5 | It registers the routers and uses the router service created at the root level. 6 | * This is important because location is a mutable global property. Having more than one object manipulating the location is not a good idea. 7 | 8 | #### How does loadChildren property work? 9 | 10 | ```ts 11 | const routes: Routes = [ 12 | ..., 13 | { path: 'edit', loadChildren: 'app/edit/edit.module#EditModule' }, 14 | ... 15 | ] 16 | ``` 17 | 18 | * In the above example, loadChildren tells the router to fetch the EditModule bundle assigned to it *when* the user visits '/edit' url. (To be more precise, it will ask the module loader to find and load it.) 19 | * Router will get the router configuration from edit module. 20 | * It merges EditModule router configuration with the main application configuration. 21 | * Activate all the needed components. 22 | 23 | #### Do you need a Routing Module? Why/not? 24 | Yes if the user was expected to navigate between different URLs. The Routing Module interprets the browser's URL as an instruction to load a specific component and its view. The application has to have its main router configured and bootstraped by passing an array of routes to `RouterModule.forRoot()`, and since this returns a module, it has to be added to the `imports` meta property in the main application module. 25 | 26 | The RouterModule: 27 | 28 | - separates our routing concerns from our feature module 29 | - provides a module to replace or remove when testing our feature module 30 | - provides a common place for require routing service providers including guards and resolvers 31 | - is not concerned with feature module declarations 32 | 33 | #### When does a lazy loaded module is loaded? 34 | 35 | The `loadChildren` property is used by the Router to map to a bundle and lazy-load it. The router will take our `loadChildren` string and dynamically load in a module, add its routes as child routes to the configuration dynamically and then load the requested route. This will only happen when the route is first requested and the module will be immediately be available for subsequent requests. 36 | 37 | Note that lazy-loaded modules should be removed from modules tehy were part of since they will be loaded on demand. 38 | 39 | 40 | #### Below link doesn't work. Why? How do I fix it? 41 | 42 | ```html 43 |
44 | ``` 45 | 46 | The routerLink should specify a defined path in the routing configuration and the required path parameter (`product.id`). The code above tries to visit a specific product page, so it should be done using *Link Parameters Array*: 47 | 48 | ```html 49 |
50 | ``` 51 | 52 | The above is correct in the case of having `product/:id` as a path in the application router configuration. 53 | 54 | 55 | #### Can you explain the difference between ActivatedRoute and RouterState? 56 | 57 | After the end of each successful navigation lifecycle, the router builds a tree of ActivatedRoute objects that make up the current state of the router. We can access the current RouterState from anywhere in our application using the Router service and the routerState property. 58 | 59 | RouterState is the current state of the router including a tree of the currently activated routes in our application along convenience methods for traversing the route tree. 60 | 61 | -------------------------------------------------------------------------------- /api.md: -------------------------------------------------------------------------------- 1 | * What does this line do: 2 | 3 | ```ts 4 | @HostBinding('class.valid') isValid; 5 | ``` 6 | 7 | Binds a host element property (here, the CSS class valid) to a directive/component property (isValid). 8 | 9 | 10 | * Why would you use renderer2 methods instead of using native element methods? 11 | 12 | Renderer2 class is an abstraction provided by Angular to manipulate elements without touching directly. Using renderer service will provide us opportunity to be able to execute manipulations in non-DOM environments like native mobile, desktop and web worker rendering. 13 | 14 | * How would you control size of an element on resize of the window in a component? 15 | * What would be a good use for NgZone service? 16 | 17 | The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don't require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via runOutsideAngular and if needed, these tasks can reenter the Angular zone via run. 18 | 19 | * What are the bootstrap options for NgZone? Why would you use them? (Angular 5+) 20 | 21 | - Provide your own `NgZone` instance. 22 | - `zone.js` - Use default `NgZone` which requires `Zone.js`. 23 | - `noop` - Use `NoopNgZone` which does nothing. You need to use async filter or manage change detection manually. 24 | 25 | source:[https://github.com/angular/angular/commit/344a5ca#diff-0ef0b3df44ffd7a42aab5233a1a3defc] 26 | 27 | * Why would you use renderer methods instead of using native element methods? 28 | 29 | You are not sure what the context you are doing the rendering. You might be assuming the browser compilation and native DOM methods to be available but that might not be the case. It is better to be safe and let Angular handle the manupulation for elements. 30 | 31 | * How would you protect a component being activated through the router? 32 | By Defning gaurds in angular like CanActivate,CanActivateChild, CanDeactivate, CanLoad (source)[https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html] 33 | Guards can be implemented in different ways, but after all it really boils down to a function that returns either Observable, Promise or boolean. In addition, guards are registered using providers, so they can be injected by Angular when needed. Check out John Papa's [guard implementation](https://github.com/johnpapa/angular-first-look-examples/blob/master/_examples/storyline-tracker/app/core/auth-guard.service.ts) 34 | 35 | * How would you insert an embedded view from a prepared `TemplateRef`? 36 | 37 | * What is the difference between @ViewChild() and @ContentChild()? 38 | 39 | - @ContentChild and @ViewChild are used to access the first element or the directive matching the selector from the content or view DOM respectively. 40 | - If the content or view DOM changes, and a new child matches the selector, the property will be updated 41 | - When static is not provided, uses query results to determine the timing of query resolution. 42 | - If any query results are inside a nested view (such as *ngIf), the query is resolved after change detection runs. 43 | - @ContentChild query is checked before @ViewChild query. 44 | 45 | @ContentChild: 46 | - Content queries are set before the *ngAfterContentInit* callback is called, after *ngOnInit* and *ngDoCheck*. 47 | - Does not retrieve elements or directives that are in other components' templates, since a component's template is always a black box to its ancestors. 48 | 49 | @ViewChild: 50 | - View queries are set before the *ngAfterViewInit* callback is called, after *ngAfterContentInit* and *ngAfterContentChecked*. 51 | - Supports querying from view DOM: 52 | - Any class with the *@Component* or *@Directive* decorator. 53 | - Template reference variable as a string (e.g. query with @ViewChild('cmp')) 54 | - Any *provider* defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService) 55 | - A *TemplateRef* (e.g. query with @ViewChild(TemplateRef) template;) 56 | -------------------------------------------------------------------------------- /ngModule.md: -------------------------------------------------------------------------------- 1 | * What is the purpose of NgModule? 2 | 3 | NgModule helps us to organize our components, directives and services into a logical unit, each focused on a feature. 4 | 5 | For example, we have 5 components in your project and that each component is dependent on other component or services or pipes then we need to import them into the respective component. And, then repeat the same process for all other components. This will become cumbersome to keep including on each of these components. This is where NgModules recuse us by importing everything to @NgModule which will be available throughout the components under one module. 6 | 7 | * How do you decide to create a new NgModule? 8 | 9 | When we are dealing with medium or large apps, it includes discrete set of functionality. Administration, Dashboard, Bookings/Orders, Promotions are all examples of areas of our apps that, when linked together, make our app. We basically breakdown our app into smaller pieces called Features / Modules. 10 | 11 | In the process of developing an app we might create a feature which we don't want to expose or create a feature which we want to lazy loading when the user decides it is time to revisit the feature. NgModules helps us to separate our features to logical units and load it when required. 12 | 13 | * What are the attributes that you can define in an NgModule annotation? 14 | * What is the difference between a module's forRoot() and forChild() methods and why do you need it? 15 | We all know that when a module provides a service and imported by a lazy loaded module, new instance of the service will be created by angular. 16 | Therefore, we usually try to avoid define services in modules that will be imported by many other module. However, there may be some cases which contradict this approach. Take a look at Angular RouterModule https://angular.io/guide/router#configuration 17 | 18 | RouterModule declares and exports some directives, e.g. router-outlet, routerLink, routerLinkActive etc. 19 | Also, it provides some services e.g. Router, ActivatedRoute etc. 20 | Take a look at the source https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts 21 | To avoid having multiple instances of services, RouterModule defines two methods, "forRoot" and "forChild". As the name suggests, "forRoot" method should be called only by root module, i.e. app.module, and forChild should be called by other feature modules. This way, you still get to use directives, components, pipes exported by this module and don't get new instances of services. 22 | If you want to define such module yourself, you can do it as following 23 | 24 | 25 | * What is providedIn property used for in an NgModule? 26 | 27 | ProvidedIn is used to specify that a service should be provided in a particular @NgModule. For example, if you don't want UserService to be available to applications unless they import a UserModule you've created, you can specify that the service should be provided in the module: 28 | ```ts 29 | @NgModule({ 30 | declarations: [MyAwesomeComponent, MyCoolDirective], 31 | exports: [MyAwesomeComponent, MyCoolDirective] 32 | }) 33 | export class MyAwesomeModule { 34 | static forRoot(): ModuleWithProviders { 35 | return { 36 | ngModule: MyAwesomeModule, 37 | providers: [MyBrilliantService] 38 | } 39 | } 40 | } 41 | ``` 42 | 43 | [Read more:](https://angular.io/guide/providers#providedin-and-ngmodules) 44 | 45 | ```ts 46 | import { Injectable } from '@angular/core'; 47 | import { UserModule } from './user.module'; 48 | 49 | @Injectable({ 50 | providedIn: UserModule, 51 | }) 52 | export class UserService { 53 | }f 54 | ``` 55 | 56 | * What would you have in a shared module? 57 | I would put directives, pipes, components and other modules that are used throughout my application and export them from this shared module. 58 | This way, I would not have to declare/import same components/modules everywhere. 59 | * What would you not put shared module? 60 | I would not put services in a shared module which may be imported by a lazy loaded module. When a lazy loaded module imports a module which provide a service, 61 | angular will create another instance of this service which may result in unexpected behaviors. 62 | * What module would you put a singleton service whose instance will be shared throughout the application (e.g. ExceptionService andLoggerService)? 63 | I would create a core module and provide all the singleton services I have from this module. I would import this module only in app.module so that, 64 | all the feature modules, even the lazy loaded ones, would use same instances of the services. 65 | * What is the purpose of exports in a NgModule? 66 | To make components/directives/pipes/modules available to other modules that import this module. 67 | * Why is it bad if SharedModule provides a service to a lazy loaded module? 68 | 69 | This question arose in the Angular Module chapter when we discussed the importance of keeping providers out of the SharedModule. 70 | 71 | Suppose we had listed the UserService in the module's providers (which we did not). Suppose every module imports this SharedModule (which they all do). 72 | 73 | When the app starts, Angular eagerly loads the AppModule and the ContactModule. 74 | 75 | Both instances of the imported SharedModule would provide the UserService. Angular registers one of them in the root app injector (see above). Then some component injects UserService, Angular finds it in the app root injector, and delivers the app-wide singleton UserService. No problem. 76 | 77 | Now consider the HeroModule which is lazy loaded! 78 | 79 | When the router lazy loads the HeroModule, it creates a child injector and registers the UserService provider with that child injector. The child injector is not the root injector. 80 | 81 | When Angular creates a lazy HeroComponent, it must inject a UserService. This time it finds a UserService provider in the lazy module's child injector and creates a new instance of the UserService. This is an entirely different UserService instance than the app-wide singleton version that Angular injected in one of the eagerly loaded components. 82 | 83 | That's almost certainly a mistake. 84 | 85 | Prove it for yourself. Run the live example. Modify the SharedModule so that it provides the UserService rather than the CoreModule. Then toggle between the "Contact" and "Heroes" links a few times. The username goes bonkers as the Angular creates a new UserService instance each time. 86 | 87 | https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-what-to-export 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular-Interview-Questions 2 | 3 | This file contains a number of [Angular](https://angular.io/) interview questions that can be used when vetting potential candidates. It is by no means recommended to use every single question here on the same candidate (that would take hours). Choosing a few items from this list should help you vet the intended skills you require. 4 | 5 | A developer is perfectly able to use Angular to build applications without being able to answer all of these questions. Addition to having a source for interview questions, my intention is to encourage interested developers to think about these questions. I regularly teach Angular workshops. Oftentimes I do not get enough questions due to limited exposure working with the framework. These questions are the ones I personally needed to answer, to be able lead a team developing our first Angular production application at Autodesk A360. 6 | 7 | **Note:** Keep in mind that many of these questions are open-ended and could lead to interesting discussions that tell you more about the person's capabilities than a straight answer would. 8 | 9 | ## Table of Contents 10 | 11 | * [Animations Questions](#animations-questions) 12 | * [Architecture Questions](#architecture-questions) 13 | * [API Questions](#api-questions) 14 | * [Template Questions](#template-syntax-questions) 15 | * [Component Questions](#component-questions) 16 | * [Component Interaction & State Management Questions](#component-interaction--state-management-questions) 17 | * [Forms Questions](#forms-questions) 18 | * [General Questions](#general-questions) 19 | * [NgModules Questions](#ngmodules-questions) 20 | * [Observables RxJS Questions](#observables-rxjs-questions) 21 | * [Performance Questions](#performance-questions) 22 | * [Pipes Questions](#pipes-questions) 23 | * [Router Questions](#router-questions) 24 | * [Services Questions](#services-questions) 25 | * [Structural Directives Questions](#structural-directives-questions) 26 | * [Styling Questions](#styling-questions) 27 | * [Style Guide Questions](#style-guide-questions) 28 | * [Testing Questions](#testing-questions) 29 | * [TypeScript Questions](#typescript-questions) 30 | * [JavaScript Questions](#javascript-questions) 31 | * [Coding Questions](#coding-questions) 32 | * [Fun Questions](#fun-questions) 33 | 34 | 35 | #### General Questions: 36 | 37 | * What did you learn about Angular yesterday/this week? 38 | * What are some of the reasons you would choose to use Angular in your project? 39 | * What did you like about working with Angular? 40 | * How do you keep your Angular code more readable and maintainable? 41 | * What does testable code mean to you in context of Angular? 42 | * What does reusable code mean to you in context of Angular? 43 | 44 | #### Animations Questions: 45 | 46 | * How do you define transition between two states in Angular? 47 | * How do you define a wildcard state? 48 | 49 | #### Architecture Questions: 50 | 51 | * What is a good use case for ngrx/store? 52 | * What is a good use case for ngrx/entity? 53 | * Can you talk about a bug related to a race condition, how to solve it and how to test it? 54 | * What is the difference between a smart/container component and dumb/presentational component? What is a good use case example? What are the advantages? 55 | 56 | #### API Questions: 57 | 58 | * What does this code do: 59 | 60 | ```ts 61 | @HostBinding('class.valid') isValid; 62 | ``` 63 | 64 | ```html 65 |
{{data}}
66 | 67 | 68 | Loading Data... 69 | 70 | ``` 71 | 72 | * Why would you use renderer methods instead of using native element methods? 73 | * How would you control size of an element on resize of the window in a component? 74 | * What would be a good use for NgZone service? 75 | * What are the bootstrap options for NgZone? Why would you use them? (Angular 5+) 76 | * How would you protect a component being activated through the router? 77 | * How would you insert an embedded view from a prepared `TemplateRef`? 78 | * What is the difference between @ViewChild() and @ContentChild() 79 | 80 | #### Template Syntax Questions: 81 | 82 | * How can you add an active class to a selected element in a list component? 83 | * What is a template variable. How would you use it? 84 | * What is the difference of using a property binding verses a function binding on a template? 85 | * What happens if you subscribe to a data source multiple times with async pipe? 86 | * What is the difference between ng-content, ng-container and ng- template? 87 | * When you create a data-binding in Angular, are you working with attributes or properties? What is the difference anyway? 88 | * When can you omit the brackets in template binding? 89 | 90 | #### Component Questions: 91 | 92 | * What is the minimum definition of a component? 93 | * What is the difference between a component and a directive? 94 | * How do components communicate with each other? 95 | * How do you create two way data binding in Angular? 96 | * How would you create a component to display error messages throughout your application? 97 | * What does a lean component mean to you? 98 | * What is the difference between a view query and a content query in Angular and how do you use view/content queries? 99 | 100 | #### Component Interaction & State Management Questions: 101 | 102 | * How would you pass data from a parent component to a child component? 103 | * How would you pass data from a child component to a parent component? 104 | * Which components will be notified when an event is emitted? 105 | * Tell me about the different ways how you would get data to your components from a service and talk about why would you use one way vs the other? 106 | * How would you use cached data? 107 | 108 | #### Forms Questions: 109 | 110 | * When do you use template driven vs model driven forms? Why? 111 | * How do you submit a form? 112 | * What's the difference between `NgForm`, `FormGroup`, and `FormControl`? How do they work together? 113 | * What's the advantage of using `FormBuilder`? 114 | * How do you add form validation to a form built with `FormBuilder`? 115 | * What's the difference between `dirty`, `touched`, and `pristine` on a form element? 116 | * How can you access validation errors in the template to display error messages? 117 | * What is async validation and how is it done? 118 | * What is the correct form control class name which is set to true when value is modified? 119 | 120 | #### NgModules Questions: 121 | 122 | * What is the purpose of NgModule? 123 | * How do you decide to create a new NgModule? 124 | * What are the attributes that you can define in an NgModule annotation? 125 | * What is the difference between a module's forRoot() and forChild() methods and why do you need it? 126 | * What is providedIn property used for in an NgModule? 127 | * What would you have in a shared module? 128 | * What would you not put shared module? 129 | * What module would you put a singleton service whose instance will be shared throughout the application (e.g. ExceptionService andLoggerService)? 130 | * What is the purpose of exports in a NgModule? 131 | * What is the difference between exports and declarations in NgModule? 132 | * Why is it bad if SharedModule provides a service to a lazy loaded module? 133 | 134 | #### Services Questions: 135 | 136 | * What is the use case of services? 137 | * How are the services injected to your application? 138 | * How do you unit test a service with a dependency? 139 | * Why is it a bad idea to create a new service in a component like the one below? 140 | 141 | ```ts 142 | let service = new DataService(); 143 | ``` 144 | 145 | #### Structural Directives Questions: 146 | 147 | * What is a structural directive? 148 | * How do you identify a structural directive in html? 149 | * When creating your own structural directives, how would you decide on hiding or removing an element? What would be the advantages or disadvantages of choosing one method rather than the other? 150 | 151 | #### Style Guide Questions: 152 | 153 | * What are some of the Angular Style Guide suggestions you follow on your code? Why? 154 | * Is it important to have a style guide? Why/not? 155 | 156 | #### Styling Questions: 157 | 158 | * How would you select a custom component to style it. 159 | * What pseudo-class selector targets styles in the element that hosts the component? 160 | * How would you select all the child components' elements? 161 | * How would you select a css class in any ancestor of the component host element, all the way up to the document root? 162 | * What selector force a style down through the child component tree into all the child component views? 163 | * What does :host-context() pseudo-class selector targets? 164 | * What does the following css do? 165 | 166 | ```css 167 | :host-context(.theme-light) h2 { 168 | background-color: red; 169 | } 170 | ``` 171 | 172 | #### Lifecycle Hooks Questions: 173 | 174 | * What is the possible order of lifecycle hooks. 175 | * When will ngOnInit be called? 176 | * How would you make use of ngOnInit()? 177 | * What would you consider a thing you should be careful doing on ngOnInit()? 178 | * What is the difference between ngOnInit() and constructor() of a component? 179 | * What is a good use case for ngOnChanges()? 180 | 181 | 182 | #### Observables RxJS Questions: 183 | 184 | * What is the difference between an observable and a promise? 185 | * What is the difference between an observable and a subject? 186 | * What are some of the angular apis that are using observables? 187 | * How would you cache an observable data? 188 | * How would you implement a multiple api calls that needs to happen in order using rxjs? 189 | * What is the difference between switchMap, concatMap and mergeMap? 190 | * How would you make sure an api call that needs to be called only once but with multiple conditions. Example: if you need to get some data in multiple routes but, once you get it, you can reuse it in the routes that needs it, therefor no need to make another call to your backend apis. 191 | * How would you implement a [brush behavior](https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172) using rxjs? 192 | * How would you implement a color picker with rxjs? 193 | * If you need to respond to two different Observable/Subject with one callback function, how would you do it?(ex: if you need to change the url through route parameters and with prev/next buttons). 194 | * What is the difference between `scan()` vs `reduce()` ? 195 | 196 | #### Performance Questions: 197 | 198 | * What are some of the things that you pay attention to, to make sure your angular application is performant? 199 | * What tools would you use to find a performance issue in your code? 200 | * What tools have you used to improve the performance of your application? 201 | * What are some ways you may improve your website's scrolling performance? 202 | * Explain the difference between layout, painting and compositing. 203 | * Have you seen Jeff Cross's NgCruise talk on performance? 204 | 205 | #### Pipes Questions: 206 | 207 | * What is a pure pipe? 208 | * What is an async pipe? 209 | * What kind of data can be used with async pipe? 210 | * How do you create a custom pipe? 211 | * How does async pipe prevents memory leeks? 212 | * What is the difference between pure and impure pipes? 213 | 214 | #### Router Questions: 215 | 216 | * What is the difference between RouterModule.forRoot() vs RouterModule.forChild()? Why is it important? 217 | * How does loadChildren property work? 218 | * Do you need a Routing Module? Why/not? 219 | * When does a lazy loaded module is loaded? 220 | * Below link doesn't work. Why? How do I fix it? 221 | 222 | ```html 223 |
224 | ``` 225 | 226 | * Can you explain the difference between ActivatedRoute and RouterState? 227 | * How do you debug router? 228 | * Why do we need route guards? 229 | * What is a RouterOutlet? 230 | 231 | #### Security Questions: 232 | 233 | 234 | #### Testing Questions: 235 | 236 | * What are some of the different tests types you can write? 237 | * How do you mock a service to inject in an integration test? 238 | * How do you mock a module in an integration test? 239 | * How do you test a component that has a dependency to an async service? 240 | * What is the difference between 'async()' and 'fakeAsync()'? 241 | 242 | #### TypeScript Questions: 243 | 244 | * Why do you need type definitions? 245 | * How would you define a custom type? 246 | * What is the difference between an Interface and a Class? 247 | * First line below gives compile error, second line doesn't. Why? 248 | 249 | ```ts 250 | someService.someMethod(x); 251 | someService['someMethod'](x); 252 | ``` 253 | 254 | * What are Discriminated union types? 255 | * How do you define Object of Objects type in typescript? 256 | * How can you capture the 'type' the user provides (e.g. number), so that we can use that information later. 257 | 258 | #### JavaScript Questions: 259 | 260 | * Explain the difference between var, let and const key words. 261 | * Could you make sure a const value is garbage collected? 262 | * Explain Object.assign and possible use cases. 263 | * Explain Object.freeze and possible use cases. 264 | * Explain the code below. How many times the createVal function is called? 265 | 266 | ```ts 267 | function createVal(){ 268 | return Math.random(); 269 | }; 270 | 271 | function fun( val = createVal()){ 272 | // Do something with val... 273 | } 274 | 275 | fun(); 276 | fun(5); 277 | 278 | ``` 279 | * What is the spread operator doing in this function call? Seriously! 280 | 281 | ``` 282 | doStuff(...args); 283 | ``` 284 | * What is destructuring assignment? 285 | * Explain why the below stand-alone syntax is not valid? 286 | 287 | ```js 288 | {a, b} = {a: 1, b: 2} 289 | ``` 290 | 291 | #### Coding Questions: 292 | 293 | * What would these components render? 294 | 295 | ```ts 296 | import { Component, ContentChildren, Directive, Input, QueryList } from '@angular/core'; 297 | 298 | @Directive({selector: 'pane'}) 299 | export class Pane { 300 | @Input() id: string; 301 | } 302 | 303 | @Component({ 304 | selector: 'tab', 305 | template: ` 306 |
panes: {{serializedPanes}}
307 | ` 308 | }) 309 | export class Tab { 310 | @ContentChildren(Pane) panes: QueryList; 311 | get serializedPanes(): string { return this.panes ? this.panes.map(p => p.id).join(', ') : ''; } 312 | } 313 | 314 | @Component({ 315 | selector: 'example-app', 316 | template: ` 317 | 318 | 319 | 320 | 321 | 322 | 323 | `, 324 | }) 325 | export class ContentChildrenComp { 326 | shouldShow = false; 327 | show() { this.shouldShow = true; } 328 | } 329 | ``` 330 | 331 | #### Fun Questions: 332 | 333 | * What's a cool project that you've recently worked on? 334 | * What are some things you like about the developer tools you use? 335 | * Who inspires you in the angular community? 336 | * Do you have any pet projects? What kind? 337 | * How did you design the architecture of your project? 338 | * What's your favorite feature of Angular? 339 | * What is your least favorite thing about Angular? (Please share your thoughts by making a pull request to [angularFeelings](https://github.com/Yonet/Angular-Interview-Questions/blob/master/angularFeelings.md)) 340 | * How do you like your coffee? 341 | * If you could decide on a new feature for angular, what would it be? 342 | * [What is Ivy and how do you enable it?](https://angular.io/guide/ivy) 343 | 344 | #### Contributors: 345 | * [Ayşegül Yönet](https://developers.google.com/experts/people/aysegul-yonet) 346 | * [Mo Atie](https://github.com/mhdatie) 347 | * [Jay Kan](https://github.com/JayKan) 348 | * [Matt Carpenter](https://github.com/mattcarp) 349 | * [Ryan Chenkie](https://github.com/chenkie) 350 | * [Shyam Chen](https://github.com/Shyam-Chen) 351 | * [Josep Sayol](https://github.com/jsayol) 352 | * [Tiep Phan](https://github.com/tieppt) 353 | * [Igor Fesenko](https://github.com/Ky7m) 354 | * [Stephan](https://github.com/styopdev) 355 | * [Bhanu Chamakuri](https://github.com/bhanu7755) 356 | * [Nanda](https://github.com/vivek4321) 357 | * [Meow Zedong](https://github.com/therealmeowzedong) 358 | * [Benjamin Cabanes](https://github.com/bcabanes) 359 | * [Bunyamin Coskuner](https://github.com/bnymncoskuner) 360 | * [Ha Hoang](https://github.com/sau-lanvy) 361 | * [Merve Ağca](https://github.com/merveagca) 362 | * [Ahmet Zeybek](https://github.com/ahmetzeybek) 363 | * [Marek Sławiński](https://github.com/mslawins) 364 | * You? 365 | --------------------------------------------------------------------------------