Visual Studio For Angular



Angular + Angular Material + NgRX + RxJS Code Snippets. Angular Snippets - Angular with. Using Angular in Visual Studio Code Welcome to Angular #. We'll be using the Angular CLI for this tutorial. To install and use the command line interface as. Let's update the sample application to 'Hello World'. Go back to the app.component.ts file and change. Debugging Angular.

AngularTools is a collection of tools for exploring an Angular project, help you with documenting, reverse engineering a project or help when refactoring.

  • Angular Support Very lightweight language support for angular definitions. Material Icon Theme The Material Icon Theme provides lots of icons based on Material Design for Visual Studio Code. It include seperate icon for example Angular-Services, Angular-Components, Angular-Directives.
  • Some developers prefer Visual Studio as their Integrated Development Environment (IDE). This cookbook describes the steps required to set up and use Angular app files in Visual Studio.

Some of the tools may seem very basic, but can be a powerful help when you have them right at your fingertips.

Find it on the Visual Studio Code marketplace.

Features

  • Show the module hierarchy
  • Show the dependency injection graph
  • Show the component hierarchy
  • Save the graphs as png, dgml or dot files
  • Summarizes all the Angular modules
  • Generate a markdown file with the component hierarchy in Mermaid format.
  • Show the directory structure of the project
  • Generate list of packages used in the project
  • List all imports

Below is a detailed description of each feature.

Show the module hierarchy #

The 'Show module hierarchy' command is used for visualizing the hierarchy of the modules in an Angular application. The command scans all the *.ts files in the project to identify classes decorated with the @NgModule class decorator and then visualize how each module is imported by other modules. It will also visualize the classes specified in the imports and the exports section of the NgModule definition.

In the visualization the classes will be colored depending on the class decorator of each class:

Visual Studio For Angular
  • Modules are red
  • Components are blue
  • Pipes are yellow
  • Directives are green

Show the dependency injection graph #

The 'Show a graph representing the components and the injected dependencies' command generates a directed graph representing the components and the services injected into the components of an Angular application. The command scans all *.ts files of the application and for each class decorated with the @Component decorator, it analyses the constructor and each field in the class to identify all injected classes and to identify all the fields decorated with the Input, Output, ViewChild, ViewChildren, ContentChild and ContentChildren decorators.

In the visualization the components will by default be colored dark blue and the injected classes will be colored light blue.

Show the component hierarchy #

The 'Show the component hierarchy' command is used for visualizing the component hierarchy and Angular application. It analyses all the *.component.ts files and all the corresponding template files to determine how the component use each other and then generates a directed graph showing the component hierarchy.

The command uses a vscode webview extension component to render the hierarchy using html, javascript and the Vis.js javascript library. This has the downside that copying the generated graph to the clipboard is not yet possible due to limitations in the vscode extension api. So to overcome this limitation the generated graph can be saved as a Png file to the root of the project you are analyzing. You can also save the graph in the Dgml format or in the GraphViz Dot format.

Save as GraphViz dot format and generate a graph from the dot file:

You can also choose to save a selection from the graph as shown in the example below.

By default the component hierarchy graph is rendered using a random layout. You can change the layout method to use a hierarchical layout to line up the nodes in the graph in different ways and also change how the layout engine sorts the nodes in the graph. This is all done by checking the 'Change layout' checkbox to show the drop down boxes with the available options.

Generate a markdown file with the component hierarchy in Mermaid format #

This command will generate the component hierarchy in markdown format using Mermaid notation.

Please notice that some online tools and sites do not support Mermaid markdown format yet, like GitHub and Visual Studio Code. To preview markdown files using the mermaid notation in Visual Studio Code i'm using the Markdown Preview Mermaid Support extension.

Generate a markdown file that summarizes all the Angular modules #

This command will scan all *.ts files in the workspace folders and find those classes that are decorated with the '@NgModule' class decorator and parse the module definition and then summarize each module into a markdown file.

The summarization will consist of two parts: First a table listing how many imports, exports, declarations and so on each module contains. The second part shows what each module contain.

Show the directory structure of the project #

This command lists the entire directory structure of the currently open project. Sometimes this can be a quick way to get an overview of the project if you are new to the project before og maybe need to document it.

The directory structure will be listed in the output window for the AngularTools extension for easy copy/pasting.

Generate list of packages used in the project #

Sometimes your boss or a customer requires documentation of which packages is used in the project. This command can save you a lot of tedious manual work by analyzing the package.json file and for each referenced package queries the npmjs.com website to fetch the description for the package and from that generates a Markdown file with a table of the packages with their descriptions.

The license information is retrieved from the package.json file for each package in the node_modules folder in the root of the workspace, this mean that the license will show 'N/A' if you have not run the 'npm install' yet.

List all imports #

This command will analyse all Angular components in the project and collect all the imports of the components together with the number of times the imported component is used. This can be useful when refactoring or identifying frequently used modules. Usually frequently used modules needs extra attention or care before being changed during refactoring. You can also use the command to identify modules that are not referenced in a consistent way where some components are using relative path and some components using path-aliases.

Settings

In the Visual Studio Code settings you find under File --> Preferences --> Settings, under Extensions, there is a section with all the settings for AngularTools. It is possible to change the default filenames used when the extension saves a file to the workspace folder. You can change how the component hierarchy graph nodes are rendered, the edge endings, the color of the root nodes and a lot more.

See the full list of settings below the screenshot.

SettingDescription
angularTools.excludeDirectoriesSemicolon separated list of directories that should be excluded when scanning for for Angular components.
angularTools.dgmlGraph.graphLayoutThis is the algorithm used to layout the nodes of the graph. Sugiyama wil try to avoid crossing edges as far as possible. ForceDirected will try to cluster the nodes.
angularTools.dgmlGraph.graphDirectionThis will make the layout algorithm position the graph nodes in the specified direction.
angularTools.dependencyInjectionGraph.pngGraphFilenameThe default name used when saving the dependency injection hierarchy graph to a Png file.
angularTools.dependencyInjectionGraph.dgmlGraphFilenameThe default filename used when saving a dependency injection hierarchy graph to a Directed Graph Markup Language (Dgml) file.
angularTools.dependencyInjectionGraph.edgeArrowToTypeThe default ending of the edges.
angularTools.showComponentHierarchy.componentHierarchyPngFilenameThe default name used when saving the component hierarchy to a Png file.
angularTools.showComponentHierarchy.componentHierarchyDgmlGraphFilenameThe default name used when saving the component hierarchy to a Dgml file.
angularTools.showComponentHierarchy.edgeArrowToTypeThe default ending of the edges.
angularTools.showModuleHierarchy.moduleHierarchyPngFilenameThe default name used when saving the module hierarchy to a Png file.
angularTools.showModuleHierarchy.moduleHierarchyDgmlGraphFilenameThe default name used when saving the module hierarchy to a Dgml file.
angularTools.showModuleHierarchy.edgeArrowToTypeThe default ending of the edges.
angularTools.graphSelection.graphSelectionGuidelineColorThe color of the guidelines used when selecting part of a component hierarchy graph. The string should be in rgb format or standard css color names.
angularTools.graphSelection.graphSelectionGuidelineWidthThe width of the guide lines shown when selecting part of a component hierarchy graph
angularTools.graphSelection.graphSelectionColorThe color of the selection rectangle used when selecting part of a component hierarchy graph. The string should be in rgb format or standard css color names.
angularTools.graphSelection.graphSelectionWidthThe width of the selection rectangle shown when selecting part of a component hierarchy graph
angularTools.graphNodes.rootNodeBackgroundColorThe color of the root nodes of the component hierarchy graph. The string should be in rgba format or standard css color names.
angularTools.graphNodes.rootNodeNodeShapeThe default shape of the nodes representing root nodes. Notice that 'ellipse','circle','database','box' and 'text' have the label inside the shape, the rest have the label outside the shape.
angularTools.graphNodes.componentNodeShapeThe default shape of the nodes representing components. Notice that 'ellipse','circle','database','box' and 'text' have the label inside the shape, the rest have the label outside the shape.
angularTools.graphNodes.moduleNodeBackgroundColorThe default color of the nodes representing modules.
angularTools.graphNodes.moduleNodeShapeThe default shape of the nodes representing modules. Notice that 'ellipse','circle','database','box' and 'text' have the label inside the shape, the rest have the label outside the shape.
angularTools.graphNodes.pipeNodeBackgroundColorThe default color of the nodes representing pipes.
angularTools.graphNodes.pipeNodeShapeThe default shape of the nodes representing pipes. Notice that 'ellipse','circle','database','box' and 'text' have the label inside the shape, the rest have the label outside the shape.
angularTools.graphNodes.directiveNodeBackgroundColorThe default color of the nodes representing directives.
angularTools.graphNodes.directiveNodeShapeThe default shape of the nodes representing directives. Notice that 'ellipse','circle','database','box' and 'text' have the label inside the shape, the rest have the label outside the shape.
angularTools.graphNodes.injectableNodeBackgroundColorThe default color of the nodes representing injected components.
angularTools.graphNodes.injectableNodeShapeThe default shape of the nodes representing directives. Notice that 'ellipse','circle','database','box' and 'text' have the label inside the shape, the rest have the label outside the shape.
angularTools.graphNodes.maximumNodeLabelLengthThe maximum length of the label for the nodes in the hierarchy. If the class name, module definition, module imports, exports, directives or pipes are longer than the specified number of characters, it will be truncated to this length.
angularTools.edges.importEdgeColorThe default color of the edges representing imports.
angularTools.edges.exportEdgeColorThe default color of the edges representing exports.
angularTools.edges.injectableEdgeColorThe default color of the edges representing injectables.
angularTools.edges.usesEdgeColorThe default color of the edges representing components using other components.
angularTools.packageJsonMarkdownFilenameThe default filename used when saving the packages.json as a markdown file.
angularTools.projectDirectoryStructureMarkdownFilenameThe default filename used when saving the project directory structure as a markdown file.
angularTools.componentHierarchyMarkdownFilenameThe default name used when saving the component hierarchy to a markdown file.
angularTools.modulesToMarkdownFilenameThe default name used when saving the project module to a markdown file.

Third party components and resources

  • Vis.js - Used for generating the directed graph for showing the component hierarchy.
  • npmjs.com - The extension queries the NpmJs.com api.
-->

The updated Angular project template provides a convenient starting point for ASP.NET Core apps using Angular and the Angular CLI to implement a rich, client-side user interface (UI).

Using Angular In Visual Studio

The template is equivalent to creating an ASP.NET Core project to act as an API backend and an Angular CLI project to act as a UI. The template offers the convenience of hosting both project types in a single app project. Consequently, the app project can be built and published as a single unit.

Create a new app

If you have ASP.NET Core 2.1 installed, there's no need to install the Angular project template.

Create a new project from a command prompt using the command dotnet new angular in an empty directory. For example, the following commands create the app in a my-new-app directory and switch to that directory:

Run the app from either Visual Studio or the .NET Core CLI:

Open the generated .csproj file, and run the app as normal from there.

The build process restores npm dependencies on the first run, which can take several minutes. Subsequent builds are much faster.

Ensure you have an environment variable called ASPNETCORE_Environment with a value of Development. On Windows (in non-PowerShell prompts), run SET ASPNETCORE_Environment=Development. On Linux or macOS, run export ASPNETCORE_Environment=Development.

Run dotnet build to verify the app builds correctly. On the first run, the build process restores npm dependencies, which can take several minutes. Subsequent builds are much faster.

Run dotnet run to start the app. A message similar to the following is logged:

Visual Studio For Angular Development

Navigate to this URL in a browser.

Visual studio for angular 7

Warning

The app starts up an instance of the Angular CLI server in the background. A message similar to the following is logged:NG Live Development Server is listening on localhost:<otherport>, open a browser to http://localhost:<otherport>/. Ignore this message—it's not the URL for the combined ASP.NET Core and Angular CLI app.

The project template creates an ASP.NET Core app and an Angular app. The ASP.NET Core app is intended to be used for data access, authorization, and other server-side concerns. The Angular app, residing in the ClientApp subdirectory, is intended to be used for all UI concerns.

Add pages, images, styles, modules, etc.

The ClientApp directory contains a standard Angular CLI app. See the official Angular documentation for more information.

There are slight differences between the Angular app created by this template and the one created by Angular CLI itself (via ng new); however, the app's capabilities are unchanged. The app created by the template contains a Bootstrap-based layout and a basic routing example.

Run ng commands

In a command prompt, switch to the ClientApp subdirectory:

If you have the ng tool installed globally, you can run any of its commands. For example, you can run ng lint, ng test, or any of the other Angular CLI commands. There's no need to run ng serve though, because your ASP.NET Core app deals with serving both server-side and client-side parts of your app. Internally, it uses ng serve in development.

If you don't have the ng tool installed, run npm run ng instead. For example, you can run npm run ng lint or npm run ng test.

Install npm packages

To install third-party npm packages, use a command prompt in the ClientApp subdirectory. For example:

Publish and deploy

In development, the app runs in a mode optimized for developer convenience. For example, JavaScript bundles include source maps (so that when debugging, you can see your original TypeScript code). The app watches for TypeScript, HTML, and CSS file changes on disk and automatically recompiles and reloads when it sees those files change.

In production, serve a version of your app that's optimized for performance. This is configured to happen automatically. When you publish, the build configuration emits a minified, ahead-of-time (AoT) compiled build of your client-side code. Unlike the development build, the production build doesn't require Node.js to be installed on the server (unless you have enabled server-side rendering (SSR)).

You can use standard ASP.NET Core hosting and deployment methods.

Run 'ng serve' independently

The project is configured to start its own instance of the Angular CLI server in the background when the ASP.NET Core app starts in development mode. This is convenient because you don't have to run a separate server manually.

There's a drawback to this default setup. Each time you modify your C# code and your ASP.NET Core app needs to restart, the Angular CLI server restarts. Around 10 seconds is required to start back up. If you're making frequent C# code edits and don't want to wait for Angular CLI to restart, run the Angular CLI server externally, independently of the ASP.NET Core process. To do so:

  1. In a command prompt, switch to the ClientApp subdirectory, and launch the Angular CLI development server:

    Important

    Use npm start to launch the Angular CLI development server, not ng serve, so that the configuration in package.json is respected. To pass additional parameters to the Angular CLI server, add them to the relevant scripts line in your package.json file.

  2. Modify your ASP.NET Core app to use the external Angular CLI instance instead of launching one of its own. In your Startup class, replace the spa.UseAngularCliServer invocation with the following:

When you start your ASP.NET Core app, it won't launch an Angular CLI server. The instance you started manually is used instead. This enables it to start and restart faster. It's no longer waiting for Angular CLI to rebuild your client app each time.

Pass data from .NET code into TypeScript code

During SSR, you might want to pass per-request data from your ASP.NET Core app into your Angular app. For example, you could pass cookie information or something read from a database. To do this, edit your Startup class. In the callback for UseSpaPrerendering, set a value for options.SupplyData such as the following:

The SupplyData callback lets you pass arbitrary, per-request, JSON-serializable data (for example, strings, booleans, or numbers). Your main.server.ts code receives this as params.data. For example, the preceding code sample passes a boolean value as params.data.isHttpsRequest into the createServerRenderer callback. You can pass this to other parts of your app in any way supported by Angular. For example, see how main.server.ts passes the BASE_URL value to any component whose constructor is declared to receive it.

Using angular in visual studio

Drawbacks of SSR

Not all apps benefit from SSR. The primary benefit is perceived performance. Visitors reaching your app over a slow network connection or on slow mobile devices see the initial UI quickly, even if it takes a while to fetch or parse the JavaScript bundles. However, many SPAs are mainly used over fast, internal company networks on fast computers where the app appears almost instantly.

At the same time, there are significant drawbacks to enabling SSR. It adds complexity to your development process. Your code must run in two different environments: client-side and server-side (in a Node.js environment invoked from ASP.NET Core). Here are some things to bear in mind:

  • SSR requires a Node.js installation on your production servers. This is automatically the case for some deployment scenarios, such as Azure App Services, but not for others, such as Azure Service Fabric.

  • Enabling the BuildServerSideRenderer build flag causes your node_modules directory to publish. This folder contains 20,000+ files, which increases deployment time.

  • To run your code in a Node.js environment, it can't rely on the existence of browser-specific JavaScript APIs such as window or localStorage. If your code (or some third-party library you reference) tries to use these APIs, you'll get an error during SSR. For example, don't use jQuery because it references browser-specific APIs in many places. To prevent errors, you must either avoid SSR or avoid browser-specific APIs or libraries. You can wrap any calls to such APIs in checks to ensure they aren't invoked during SSR. For example, use a check such as the following in JavaScript or TypeScript code:

Additional resources