search
HomeWeb Front-endJS Tutorial12 classic interview questions about Angular

12 classic interview questions about Angular

Angular As the most popular front-end framework at present, it is generally welcomed by front-end developers. Whether you are new to Angular or a developer with some Angular development experience, understanding the 12 classic interview questions in this article will be an excellent way to deeply understand and learn the knowledge and concepts of Angular 2.

In this article, we will be exposed to many important concepts of Angular 2, and attached are extended reading materials and self-examination tests for everyone to evaluate their understanding of Angular.

Recommended related tutorials: "angular Tutorial"

Angular Classic Questions and Extended Reading

1. Please explain what are the life cycle hooks of Angular 2 applications?

Angular 2 components/directives have life cycle events, which are managed by @angular/core. @angular/core creates the component, renders it, and creates and renders its descendants. When the data binding properties of @angular/core change, the handling changes, destroying its template before removing it from the DOM. Angular provides a set of life cycle hooks (special events) that can be branched into the life cycle and perform operations when needed. The constructor is executed before all life cycle events. Each interface has a hook method prefixed with ng. For example, the OnInit method of the ngOnint interface, this method must be implemented in the component.

Some events are applicable to components/directives, while a few events are only applicable to components.

  • ngOnChanges: Responds when Angular sets its data-bound properties that receive the current and previous object values.
  • ngOnInit: After the first ngOnChange trigger, initialize the component/directive. This is the most commonly used method for retrieving a template's data from a backend service.
  • ngDoCheck: Detect and execute when the Angular context changes. Will be called every time change detection is run.
  • ngOnDestroy: Clear before Angular destroys the directive/component. Unsubscribe from observables and disengage event handlers to avoid memory leaks.

Component specific hooks:

  • ngAfterContentInit: The component content has been initialized
  • ngAfterContentChecked: Outside of Angular checks for bindings projected into its view After the content.
  • ngAfterViewInit: After Angular creates the component’s view.
  • ngAfterViewChecked: After Angular checks the binding of the component view.

2. What are the advantages of using Angular 2 compared to using Angular 1?

  • Angular 2 is a platform, not just a language

  • Better speed and performance

  • Simpler dependency injection

  • Modular, cross-platform

  • With the benefits of ES6 and Typescript.

  • Flexible routing with lazy loading function

  • Easier to learn

3. How does routing work in Angular 2?

Routing is a mechanism that enables users to navigate between views/components. Angular 2 simplifies routing and provides flexibility to configure and define at the module level (lazy loading).

Angular applications have a single instance of the router service, and whenever the URL changes, the corresponding route is matched against the route configuration array. On a successful match, it applies the redirect, at which point the router builds a tree of ActivatedRoute objects, including the router's current state. Before redirecting, the router will check whether the new state is allowed by running the guard (CanActivate). Route Guard is simply an interface method that routers run to check route authorization. Once the protection is running, it parses the routing data and activates the router state by instantiating the required components into .

Extended reading:

  • https://www.codeproject.com/Articles/1164813/Angular-Routing

  • https://vsavkin.com/angular-2-router-d9e30599f9ea#.kt4z1v957

4. What is an event emitter? How does it work in Angular 2?

Angular 2 does not have a bidirectional digest cycle, which is different from Angular 1. In Angular 2, any changes that occur in a component are always propagated from the current component to all its child components. If changes to a child component need to be reflected in the hierarchy of its parent component, we can emit events by using the event emitter API.

In short, EventEmitter is a class defined in the @angular/core module and used by components and directives to emit custom events.

@output() somethingChanged = new EventEmitter();

We use somethingChanged.emit(value) method to emit the event. This is typically used in setters when a value in the class has been changed.

You can use the subscription method to implement event emission subscription through any component of the module.

myObj.somethingChanged.subscribe(val) => this.myLocalMethod(val));

Extended reading:

  • ##http://stackoverflow.com/questions/36076700/what-is- the-proper-use-of-an-eventemitter

  • https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.HTML

#5. How to use codelyzer in Angular 2 application?

All enterprise applications follow a set of coding conventions and guidelines to maintain the code in a better way. Codelyzer is an open source tool for running and checking whether predefined coding guidelines are followed. Codelyzer only performs static code analysis on Angular and TypeScript projects.

Codelyzer runs on top of tslint, and its coding conventions are usually defined in the tslint.json file. Codelyzer can be run directly through Angularcli or npm. Editors like Visual Studio Code and Atom also support codelyzer, which only requires a basic setup.

To set up codelyzer in Visual Studio Code, we can add the path to the tslint rule in File - > Options - > User Settings.

{

    "tslint.rulesDirectory": "./node_modules/codelyzer",

    "typescript.tsdk": "node_modules/typescript/lib"

}
Code run from cli: ng lint.

Code run from npm: npm run lint

Extended reading:

  • https ://github.com/mgechev/codelyzer

  • https://www.youtube.com/watch?v=bci-Z6nURgE

6. What is lazy loading? How to enable lazy loading in Angular 2?

Most enterprise applications contain a variety of modules for specific business cases. Bundling the entire application code and loading it creates a huge performance overhead on the initial call. Lazy loading allows us to load only the modules that the user is interacting with, while the rest are loaded on demand at runtime.

Lazy loading speeds up the initial loading process of an application by splitting the code into multiple packages and loading them on demand.

Every Angular application must have a main module called AppModule. The code should be divided into different sub-modules (NgModules) based on the application business case.

Plunkr example with lazy loading enabled:

  • We don’t need to import or declare lazy loading modules in the root module.

  • Add the route to the top-level route (app.routing.ts) and set loadChildren. loadChildren will get the absolute path from the root folder. RouterModule.forRoot() will get the routes array and configure the router.

  • Import module specific routes in submodules.

  • In submodule routing, specify the path as the empty string "", which is an empty path. RouterModule.forChild will again use the route array to load and configure the router for the submodule component.

  • Then, export the const route: ModuleWithProviders = RouterModule.forChild(routes);

7. In Angular 2 What security threats should we pay attention to in applications?

Just like any other client or web application, Angular 2 applications should also follow some basic guidelines to mitigate security risks. Some of them are:

  • Avoid using/injecting dynamic HTML content for your components.

  • If you use external HTML, that is, from somewhere outside the database or application, then you need to clean it.

  • Don't put external URLs in the application unless it is trusted. Avoid URL redirection unless it is trusted.

  • Consider using AOT compilation or offline compilation.

  • Prevent XSRF attacks by restricting APIs and choosing apps that use known or safe environments/browsers.

Extended readinghttps://angular.io/docs/ts/latest/guide/security.HTML#!#best -practices

8. How to optimize Angular 2 applications for better performance?

Optimization depends on the type and size of the application and many other factors. But generally speaking, when optimizing an Angular 2 application, I would consider the following:

  • Consider AOT compilation.

  • Make sure the application has gone through bundling, uglify and tree shaking.

  • Ensure that there are no unnecessary import statements in the application.

  • Make sure that unused third-party libraries have been removed from the application.

  • All dependencies and dev-dependencies are clearly separated.

  • If the application is larger, I would consider lazy loading instead of a fully bundled application.

Extended reading:

  • ##https://medium.com/@areai51/ the-4-stages-of-perf-tuning-for-your-angular2-app-922ce5c1b294#.pw4m2srmr

  • https://www.lucidchart.com/techblog/2016/ 05/04/angular-2-best-practices-change-detector-performance/

9. How to implement a custom type without editor warnings?

In most cases, the third-party library comes with its .d.ts file for type definition. In some cases we need to extend an existing type by providing it with some more properties, or if we need to define other types to avoid TypeScript warnings.

If we need to extend the type definition of an external library, a good approach is that instead of making changes to the node_modules or existing typings folder, we create a new file named "custom type" folder to store all custom types.

To define the type of application (JavaScript/Typescript) object, we should define the interface and entity class in the models folder of the corresponding module of the application.

For these cases, we can define or extend the type by creating our own ".d.ts" file.

Extended reading:

  • https://www.typescriptlang.org/docs/handbook/declaration-merging .HTML

  • https://typescript.codeplex.com/wikipage?title=Writing Definition (.d.ts) Files

  • http ://stackoverflow.com/questions/32948271/extend-interface-defined-in-d-ts-file

10. What is Shadow DOM? How does it help Angular 2 perform better?

Shadow DOM is part of the HTML specification that allows developers to encapsulate their own HTML markup, CSS styles and JavaScript. Shadow DOM, along with other technologies, enables developers to build their own first-level tags, Web components and APIs like the

The above is the detailed content of 12 classic interview questions about Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!