<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>angular tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/angular-tips/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Wed, 16 Aug 2023 06:33:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>angular tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Improve Your Angular Performance?</title>
		<link>https://topreviewhostingasp.net/how-to-improve-your-angular-performance/</link>
					<comments>https://topreviewhostingasp.net/how-to-improve-your-angular-performance/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Wed, 16 Aug 2023 06:33:38 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular performance]]></category>
		<category><![CDATA[angular tips]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3686</guid>

					<description><![CDATA[A very well-liked and widely used framework for creating contemporary web applications is Angular. This technology has a ton of features and is very powerful. As a web developer, you already have everything you need, and Angular makes it simple to configure, maintain, and grow any application created using the framework. You&#8217;ve probably already created [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>A very well-liked and widely used framework for creating contemporary web applications is Angular. This technology has a ton of features and is very powerful. As a web developer, you already have everything you need, and Angular makes it simple to configure, maintain, and grow any application created using the framework.</p>
<p>You&#8217;ve probably already created one or more Angular applications by this point, but are they ideal?</p>
<h2 id="how-to-improve-angular-apps-performance"><b>How to Improve The Performance of Angular Applications</b></h2>
<p>I&#8217;ve created a sample Angular application that I&#8217;ll use in this article. The following features and libraries are used by the application as of the time this article was written:</p>
<h3 id="angular-build" class="graf graf--h4">Angular Build</h3>
<p>When I run the application in a development environment, everything seems to be working perfectly, but the initial lighthouse score is not very good:</p>
<p><img fetchpriority="high" decoding="async" class="wp-image-3687 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular.png" alt="" width="646" height="661" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular.png 847w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-293x300.png 293w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-768x786.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-50x50.png 50w" sizes="(max-width: 646px) 100vw, 646px" /></p>
<p>I can see where the problems are coming from when I look at the recommendations for enhancing the lower-scoring sections. The size of the resources (JavaScript, styles, and static resources) transferred to the client is the first significant problem.</p>
<p><img decoding="async" class="wp-image-3688 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-2.png" alt="" width="698" height="715" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-2.png 847w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-2-293x300.png 293w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-2-768x786.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-2-50x50.png 50w" sizes="(max-width: 698px) 100vw, 698px" /></p>


<p>Running a production build of my Angular application rather than a development one will quickly fix this problem.Prior to deployment, always build with the production configuration. This will take care of the warning to make JavaScript and CSS smaller. To see how the production build differs, let&#8217;s look at the angular.json file located at the root of our Angular repository:</p>



<pre class="wp-block-code"><code>"configurations": {
  "production": {
    "budgets": &#91;
      {
        "type": "initial",
        "maximumWarning": "2mb",
        "maximumError": "5mb"
      },
      {
        "type": "anyComponentStyle",
        "maximumWarning": "10kb"
      }
    ],
    "fileReplacements": &#91;
      {
        "replace": "projects/common/src/environments/environment.ts",
        "with": "projects/common/src/environments/environment.prod.ts"
      }
    ],
    "localize": true,
    "optimization": true,
    "outputHashing": "all",
    "sourceMap": false,
    "namedChunks": false,
    "extractLicenses": true,
    "vendorChunk": false,
    "buildOptimizer": true,
    "serviceWorker": true,
    "i18nMissingTranslation": "error",
    "ngswConfigPath": "projects/bellumgens/src/ngsw-config.json"
  },
  "bg": {
    "localize": &#91;
      "bg"
    ]
  }
}</code></pre>



<p>There are numerous configurations present. The &#8220;optimization&#8221;: true one is, however, the most crucial in this situation. In terms of load-time performance, the difference in score is sizable once I run the application with a production configuration:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-3.png" alt="" class="wp-image-3689" width="673" height="688" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-3.png 847w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-3-293x300.png 293w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-3-768x786.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-3-50x50.png 50w" sizes="(max-width: 673px) 100vw, 673px" /></figure></div>


<p>The number of suggestions is significantly less if I take another look at the list of opportunities. The biggest opportunities for text compression are the caching of static resources and unused JavaScript:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-4.png" alt="" class="wp-image-3690" width="704" height="720" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-4.png 847w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-4-293x300.png 293w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-4-768x786.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-4-50x50.png 50w" sizes="(max-width: 704px) 100vw, 704px" /></figure></div>


<h3 class="wp-block-heading">Angular Pre-Rendering and Server-Side Rendering </h3>



<p>A single page application (SPA) framework is Angular. By default, the app&#8217;s lifecycle is set up so that, in response to a client request, the server that hosts the application sends a file of HTML that contains all the required script and style references. However, the body content is missing. The application is bootstrapped and filled with content according to the JavaScript logic for the given application after the scripts and styles have been requested and served. In order to enhance this lifecycle, Angular offers two mechanisms that serve actual content in the initial HTML document. To accomplish this, the application&#8217;s JavaScript logic must be run before the document is served. How to go about it:</p>



<ul><li>Either at build time (<a href="https://angular.io/guide/prerendering">pre-rendering</a>) &#8211; for pages with mostly static content. </li><li>Or at run time on the server (<a href="https://angular.io/guide/universal">server-side rendering</a>) - for pages with more dynamic content that need to deliver up-to-date content on every request. </li></ul>



<p>For the Angular example app, I have enabled server-side rendering, and I&#8217;m using the <a href="https://expressjs.com/" target="_blank" rel="noreferrer noopener">express engine</a> to enable text compression and static resource caching. The following is added to my express server logic to achieve this:</p>



<pre class="wp-block-code"><code>export const app = (lang: string) => {
  // server scaffolded by &#91;ng add @nguniversal/express-engine]
...
  // enable compression &#91;npm install compression]
  const compression = require('compression');
  server.use(compression());
...
  // Serve static files from /browser with 1y caching
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));
...
}</code></pre>



<p>I&#8217;ll perform server-side rendering for the app and repeat the lighthouse test. The speed index was lowered to 1.2 seconds while the initial load improved even more, bringing the first contentful paint to under a second.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-5.png" alt="" class="wp-image-3691" width="710" height="726" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-5.png 847w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-5-293x300.png 293w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-5-768x786.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-5-50x50.png 50w" sizes="(max-width: 710px) 100vw, 710px" /></figure></div>


<p>Reducing unused JavaScript and CSS is one of the final optimization opportunities for Angular.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-6.png" alt="" class="wp-image-3692" width="725" height="313" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-6.png 847w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-6-300x130.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-6-768x333.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-6-50x22.png 50w" sizes="(max-width: 725px) 100vw, 725px" /></figure></div>


<p>To deal with these, I will have to do some application refactoring.</p>



<h3 class="wp-block-heading">Angular Lazy-Loading </h3>



<p>The best strategy for reducing the amount of unused JavaScript would be to create routes that are <a href="https://angular.io/guide/lazy-loading-ngmodules" target="_blank" rel="noreferrer noopener">lazy-loaded</a>. This will divide the JavaScript into modules, the logic for which is loaded only when the requested route is loaded, and inform the Angular framework which components are not required in the top-level module.</p>



<p>The Angular example app I&#8217;m using for this blog makes use of larger components that aren&#8217;t included in the home route, like the igx-grid. I&#8217;m creating a separate module for the routes that use this component. In this manner, the component will only be loaded after the routes that use it have been loaded. The routes appear as follows after the modules have been separated:</p>



<pre class="wp-block-code"><code>export const routes: Routes = &#91;
  { path: '', component: HomeComponent },
  { path: 'register', component: RegistrationComponent },
  { path: 'unauthorized', redirectTo: 'unauthorized/', pathMatch: 'full' },
  { path: 'unauthorized/:message', component: UnauthorizedComponent },
  { path: 'emailconfirm', component: EmailconfirmComponent },
  { path: 'strategies', loadChildren: () => import('./strategies/strategies.module').then(m => m.StrategiesModule) },
  { path: 'emailconfirm/:error', component: EmailconfirmComponent },
  { path: 'players', loadChildren: () => import('./player-section/player.module').then(m => m.PlayerModule) },
  { path: 'team', loadChildren: () => import('./team-section/team.module').then(m => m.TeamModule) },
  { path: 'notifications', loadChildren: () => import('./notifications/notifications.module').then(m => m.NotificationsModule) },
  { path: 'search/teams/:query', component: TeamResultsComponent },
  { path: 'search/players/:query', component: PlayerResultsComponent },
  { path: '**', component: HomeComponent }
];</code></pre>



<p>The <code>team.module</code> is the one loading the grid I’m using, so the code for it looks like this:</p>



<pre class="wp-block-code"><code>@NgModule({
  imports: &#91;
    CommonModule,
    FormsModule,
    // ...
    IgxGridModule,
    // ...
    TeamComponent,
    // ...
  ]
})
export class TeamModule { }</code></pre>



<p>Looking at the build, the initial splitting produced the following:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-7.png" alt="" class="wp-image-3693" width="615" height="221" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-7.png 746w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-7-300x108.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-7-50x18.png 50w" sizes="(max-width: 615px) 100vw, 615px" /></figure></div>


<p>Limiting the size of the CSS to the styles that are used is another thing that must be done to enhance the performance of the Angular application.</p>



<h3 class="wp-block-heading">Optimizing Images </h3>



<p>The images should be optimized as part of the Angular optimization process. You can use Lighthouse check to determine whether the type or size of your images are insufficient. Make sure the images you load are optimized for encoding and are not larger than the containers they go in. I now save my images in.webp format. Although it slightly lowers the quality, the application still does not require the highest fidelity images.</p>



<p>After being loaded, images cause changes to the layout. In order for the browser to be aware of the dimensions prior to loading the images, it is a good idea to set width and height attributes on the images. Lighthouse will alert you if the images&#8217; aspect-ratio settings (width and height) are missing. The layout shifts will be lessened or eliminated as a result.</p>



<h3 class="wp-block-heading">NgOptimizedImage to Enforce Image Best Practices </h3>



<p>For your benefit, Angular exposes a directive that upholds image best practices and streamlines image loading. Its name is <a href="https://angular.io/api/common/NgOptimizedImage" target="_blank" rel="noreferrer noopener">NgOptimizedImage</a>, and using it is fairly simple. If your Angular application is still using NgModules, all you have to do is import CommonModule, or import NgOptimizedImage in the component you want to use it in. Then you use ngSrc to set the image source attribute rather than src.</p>



<pre class="wp-block-code"><code>&lt;img ngSrc="/assets/wallpapers/strat-editor.webp" width="600" height="347" class="preview-image" alt="Strategy Editor" /></code></pre>



<p>Finally, you can specify the order in which each image should load and instruct the app to lazy-load all non-critical images. If I run the app without the width and height attributes, what I get is:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-8.png" alt="" class="wp-image-3694" width="771" height="157" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-8.png 1001w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-8-300x61.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-8-768x157.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-8-50x10.png 50w" sizes="(max-width: 771px) 100vw, 771px" /></figure></div>


<p>And that’s it. </p>



<h2 class="wp-block-heading">Final Verdict</h2>



<p>In order to ensure that Angular applications operate effectively and dependably under a variety of circumstances, performance improvement may necessitate ongoing monitoring, optimization, and best practices. But in the end, this is how you provide the best UX, draw in and keep users, stay competitive, and grow your business.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-improve-your-angular-performance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Setup Angular Code in ASP.NET Core Project</title>
		<link>https://topreviewhostingasp.net/setup-angular-code-in-asp-net-core-project/</link>
					<comments>https://topreviewhostingasp.net/setup-angular-code-in-asp-net-core-project/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 10 Aug 2023 03:55:42 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[angular tutorial]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3681</guid>

					<description><![CDATA[Due to their low weight and high performance, Single-Page Applications, or SPAs, have recently become the most sought-after client facing application stacks. In this architecture, the client application renders the fetched data onto a fluid and dynamic layout while the server concentrates on data logic and provides data to the client in the form of [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Due to their low weight and high performance, Single-Page Applications, or SPAs, have recently become the most sought-after client facing application stacks. In this architecture, the client application renders the fetched data onto a fluid and dynamic layout while the server concentrates on data logic and provides data to the client in the form of RESTful APIs.</p>



<p>In addition to improving user experience, this can lessen the load placed on the webserver when rendering and serving HTML content over the network. In order to create the most effective SPAs, client-side frameworks like Angular, ReactJs, and Ionic have advanced significantly. Let&#8217;s discuss how to integrate an SPA powered by Angular inside of an existing ASP.NET Core application in this article.</p>



<p>Assume that the data source for an Angular application is an ASP.NET Core application. We now have two options for deployment: running two instances of both the client and server applications, with the client application configured with the server endpoint. Most of the real-world application deployments we see today are done in this manner.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>A webserver like IIS or Apache must once again host an SPA, which is simply an index.html page with a few js files for runtime and client logic.</p></blockquote>



<p>An innovative method has been developed that sandwiched an angular SPA inside an ASP.NET Core API because we would also need to require the client application to maintain the server address for communication.</p>



<p>With this method, both applications can be created and deployed on a single instance, and they are both local to one another. When a user calls the appropriate routes, the ASPNETCORE application also serves the client application to them. A few libraries must be added to the ASP.NET Core API, and the csproj file must be modified to allow for angular build activities.</p>



<h2 class="wp-block-heading">Steps to Implement Code in ASP.NET Core</h2>



<p>1. Start by copying the Angular application into the ClientApp subdirectory of the ASPNETCORE project. Together with the controllers and other projects, this is located in the root directory. Just keep in mind that since we&#8217;re using an ASPNETCORE API project, we don&#8217;t have a wwwroot folder or Views folder.</p>



<p>2. Install the package listed below, which supports SPA building and rendering, in the ASPNETCORE project.</p>



<pre class="wp-block-preformatted">&lt;PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="3.1.3" /&gt;</pre>



<p>3. To support SPA, we would need to add a few middlewares and services to the Startup class. The server application would route to an SPA when making specific requests technically because it is just a collection of static files under the ASPNETCORE project. We would also add support for the server to access these static files in order to make this possible.</p>



<p>The middleware functions UseStaticFiles() and UseSpa() for SPA support accomplish this.</p>



<pre class="wp-block-code"><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
            
    // In production, the Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
}</code></pre>



<pre class="wp-block-code"><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseStaticFiles();
    
    // In Production Environment
    // Serve Spa static files
    if (!env.IsDevelopment())
    {
        app.UseSpaStaticFiles();
    }

    // other ASPNETCORE Routing Code
    // Spa middleware to enable
    // SPA request handling
    app.UseSpa(spa =>
    {
        // The directory from which the 
        // SPA files shall be served for
        // client requests
        spa.Options.SourcePath = "ClientApp";

        // When in Development,
        // Since the SPA app is not build
        // use npm start command to run 
        // the node server for local run
        if (env.IsDevelopment())
        {
            spa.UseAngularCliServer(npmScript: "start");
        }
    });
}</code></pre>



<p>4. We make sure the angular build command configuration in the angular.json file of the client application, which is under the ClientApp directory, so that on angular build, the files are created under the /dist folder relative to the Client app path.</p>



<pre class="wp-block-code"><code>        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "progress": false,
            "extractCss": true,
            "outputPath": "dist", &lt;-- ensure this path
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": &#91;"src/assets"],
            "styles": &#91;
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],
            "scripts": &#91;]
          }
        }</code></pre>



<p>This is significant because, when running, the ASPNETCORE application searches for the Spa files under the services-specified path /ClientApp/dist folder.Method AddSpaStaticFiles().</p>



<p>5. Finally, using the csproj and the changes listed below, we wire up the ClientApp and ASPNETCORE app together during project build.</p>



<pre class="wp-block-code"><code>&lt;ItemGroup>
    &lt;!-- Don't publish the SPA source files, but do show them in the project files list -->
    &lt;Content Remove="$(SpaRoot)**" />
    &lt;None Remove="$(SpaRoot)**" />
    &lt;None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules**" />
  &lt;/ItemGroup></code></pre>



<pre class="wp-block-code"><code>&lt;!-- Debug run configuration -->
  &lt;!-- Check for Nodejs installation, install in the ClientApp -->
  &lt;Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    &lt;!-- Ensure Node.js is installed -->
    &lt;Exec Command="node --version" ContinueOnError="true">
      &lt;Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    &lt;/Exec>
    &lt;Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    &lt;Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    &lt;Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  &lt;/Target></code></pre>



<pre class="wp-block-code"><code>&lt;!-- Publish time tasks: run npm build along with project publish -->
  &lt;Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    &lt;!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    &lt;Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    &lt;Exec WorkingDirectory="$(SpaRoot)" Command="npm run build -- --prod" />
    &lt;Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --prod" Condition=" '$(BuildServerSideRenderer)' == 'true' " />

    &lt;!-- Include the newly-built files in the publish output -->
    &lt;ItemGroup>
      &lt;DistFiles Include="$(SpaRoot)dist**; $(SpaRoot)dist-server**" />
      &lt;DistFiles Include="$(SpaRoot)node_modules**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
      &lt;ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        &lt;RelativePath>%(DistFiles.Identity)&lt;/RelativePath>
        &lt;CopyToPublishDirectory>PreserveNewest&lt;/CopyToPublishDirectory>
        &lt;ExcludeFromSingleFile>true&lt;/ExcludeFromSingleFile>
      &lt;/ResolvedFileToPublish>
    &lt;/ItemGroup>
  &lt;/Target></code></pre>



<p>In each of these configurations, we define $(SpaRoot) at the top of the csproj file as the ClientApp rootpath:</p>



<pre class="wp-block-code"><code>&lt;PropertyGroup>
    &lt;TargetFramework>netcoreapp3.1&lt;/TargetFramework>
    &lt;TypeScriptCompileBlocked>true&lt;/TypeScriptCompileBlocked>
    &lt;TypeScriptToolsVersion>Latest&lt;/TypeScriptToolsVersion>
    &lt;IsPackable>false&lt;/IsPackable>

    &lt;!-- the path picked up by all the processing -->
    &lt;SpaRoot>ClientApp&lt;/SpaRoot>
    &lt;DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules**&lt;/DefaultItemExcludes>
    &lt;!-- Set this to true if you enable server-side prerendering -->
    &lt;BuildServerSideRenderer>false&lt;/BuildServerSideRenderer>
&lt;/PropertyGroup></code></pre>



<p>When everything is finished, we can simply publish our project.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build.webp" alt="" class="wp-image-3682" width="761" height="407" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build.webp 847w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-300x160.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-768x411.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-50x27.webp 50w" sizes="(max-width: 761px) 100vw, 761px" /></figure></div>


<p>and run to see our changes coming into effect.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-run.webp" alt="" class="wp-image-3683" width="809" height="367" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-run.webp 848w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-run-300x136.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-run-768x349.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/08/angular-build-run-50x23.webp 50w" sizes="(max-width: 809px) 100vw, 809px" /></figure></div>]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/setup-angular-code-in-asp-net-core-project/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Use WebSocket to Push Real-Time Data to an Angular Service</title>
		<link>https://topreviewhostingasp.net/how-to-use-websocket-to-push-real-time-data-to-an-angular-service/</link>
					<comments>https://topreviewhostingasp.net/how-to-use-websocket-to-push-real-time-data-to-an-angular-service/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Tue, 13 Dec 2022 04:37:09 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular service]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[websocket]]></category>
		<category><![CDATA[websocket tips]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3304</guid>

					<description><![CDATA[Pushing data from the server to the client is useful when applications need to display real-time data or when they want to leverage the speed and low-latency benefits provided by TCP/IP Web Socket connections. In this article tutorial, I will give how to demonstrate the process above. 1. Add Web Socket Functionality to the Server [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Pushing data from the server to the client is useful when applications need to display real-time data or when they want to leverage the speed and low-latency benefits provided by TCP/IP Web Socket connections.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="360" class="wp-image-862 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs.png 640w, https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs-300x169.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2017/11/angularjs-50x28.png 50w" sizes="(max-width: 640px) 100vw, 640px" /></figure></div>


<p>In this article tutorial, I will give how to demonstrate the process above.</p>



<p><strong>1. Add Web Socket Functionality to the Server</strong></p>



<p>There are a lot of options that can be used to add Web Socket functionality to the server – it really depends upon what language/framework you prefer. For the Angular/Web Socket example project, I went with Node.js and <a href="https://socket.io/" target="_blank" rel="noreferrer noopener">socket.io</a> since it’s easy to get up and running on any OS. The overall server is extremely easy to get up and running (keep in mind that I purposely kept it very basic to demonstrate the overall concept). The server starts a timer (used to simulate data changing on the server) once a client connection is made and returns data to one or more clients as the timer fires.</p>



<pre class="wp-block-code"><code>const express = require('express'),
      app = express(),
      server = require('http').createServer(app);
      io = require('socket.io')(server);

let timerId = null,
    sockets = new Set();

//This example emits to individual sockets (track by sockets Set above).
//Could also add sockets to a "room" as well using socket.join('roomId')
//https://socket.io/docs/server-api/#socket-join-room-callback

app.use(express.static(__dirname + '/dist')); 

io.on('connection', socket =&gt; {

  sockets.add(socket);
  console.log(`Socket ${socket.id} added`);

  if (!timerId) {
    startTimer();
  }

  socket.on('clientdata', data =&gt; {
    console.log(data);
  });

  socket.on('disconnect', () =&gt; {
    console.log(`Deleting socket: ${socket.id}`);
    sockets.delete(socket);
    console.log(`Remaining sockets: ${sockets.size}`);
  });

});

function startTimer() {
  //Simulate stock data received by the server that needs 
  //to be pushed to clients
  timerId = setInterval(() =&gt; {
    if (!sockets.size) {
      clearInterval(timerId);
      timerId = null;
      console.log(`Timer stopped`);
    }
    let value = ((Math.random() * 50) + 1).toFixed(2);
    //See comment above about using a "room" to emit to an entire
    //group of sockets if appropriate for your scenario
    //This example tracks each socket and emits to each one
    for (const s of sockets) {
      console.log(`Emitting value: ${value}`);
      s.emit('data', { data: value });
    }

  }, 2000);
}

server.listen(8080);
console.log('Visit http://localhost:8080 in your browser');</code></pre>



<p>The key part of the code is found in the <strong>io.on(‘connection’, …)</strong> section. This code handles adding client socket connections into a set, starts the timer when the first socket connection is made and handles removing a given socket from the set when a client disconnects. The <strong>startTimer()</strong> function simulates data changing on the server and handles iterating through sockets and pushing data back to connected clients (note that there are additional techniques that can be used to push data to multiple clients – see the included comments).</p>



<p>The next 3 steps all relate to the Angular service.</p>



<p>2. Create an Angular Service that Subscribes to the Data Stream Provided by the Server</p>



<p>3. Return an Observable from the Angular Service that a Component can Subscribe to</p>



<p>4. Emit data received in the Angular Service (from the service) to Observable subscribers</p>



<p>The Angular service subscribes to the data being pushed from the server using a script provided by socket.io (the script is defined in index.html). The service’s <strong>getQuotes()</strong> function first connects to the server using the <strong>io.connect()</strong> call. It then hooks the returned socket to “data” messages returned from the server. Finally, it returns an <strong>observable</strong> to the caller. The <strong>observable</strong> is created  by calling<strong> Observable.create()</strong> in the <strong>createObservable()</strong> function.</p>



<p>As Web Socket data is received in the Angular service, the observer object created in <strong>createObservable()</strong> is used to pass the data to any Angular subscribers by calling <strong>observer.next(res.data)</strong>. In essence, the Angular service simply forwards any data it receives to subscribers.</p>



<pre class="wp-block-code"><code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { map, catchError } from 'rxjs/operators';
import * as socketIo from 'socket.io-client';

import { Socket } from '../shared/interfaces';

declare var io : {
  connect(url: string): Socket;
};

@Injectable()
export class DataService {

  socket: Socket;
  observer: Observer;

  getQuotes() : Observable&lt;number&gt; {
    this.socket = socketIo('http://localhost:8080');

    this.socket.on('data', (res) =&gt; {
      this.observer.next(res.data);
    });

    return this.createObservable();
  }

  createObservable() : Observable&lt;number&gt; {
      return new Observable(observer =&gt; {
        this.observer = observer;
      });
  }

  private handleError(error) {
    console.error('server error:', error);
    if (error.error instanceof Error) {
        let errMessage = error.error.message;
        return Observable.throw(errMessage);
    }
    return Observable.throw(error || 'Socket.io server error');
  }

}</code></pre>



<p><strong>5. Subscribe to the Service Observable in a Component</strong></p>



<p>The final step involves a component subscribing to the observable returned from the service’s <strong>getQuotes()</strong> function. In the following code, <strong>DataService</strong> is injected into the component’s constructor and then used in the <strong>ngOnOnit()</strong> function to call <strong>getQuotes()</strong> and subscribe to the observable. Data that streams into the subscription is fed into a <strong>stockQuote</strong> property that is then rendered in the UI.</p>



<p>Note that the subscription object returned from calling <strong>subscribe()</strong> is captured in a <strong>sub</strong> property and used to unsubscribe from the <strong>observable</strong> when <strong>ngOnDestroy()</strong> is called.</p>



<pre class="wp-block-code"><code>import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataService } from './core/data.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {

  stockQuote: number;
  sub: Subscription;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.sub = this.dataService.getQuotes()
        .subscribe(quote =&gt; {
          this.stockQuote = quote;
        });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}</code></pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Although this example is intentionally kept quite simple (there’s much more that could be added), it hopefully provides a nice starting point if you’re interested in streaming data to an Angular service using Web Sockets.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-use-websocket-to-push-real-time-data-to-an-angular-service/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Angular Tips &#8211; Build Clean Forms Using Reactive Forms</title>
		<link>https://topreviewhostingasp.net/angular-tips-build-clean-forms-using-reactive-forms/</link>
					<comments>https://topreviewhostingasp.net/angular-tips-build-clean-forms-using-reactive-forms/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 25 Aug 2022 04:21:47 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[angular tutorial]]></category>
		<category><![CDATA[clean forms angular]]></category>
		<category><![CDATA[formbuilder angular]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3142</guid>

					<description><![CDATA[Reactive forms in Angular enable you to build clean forms without using too many directives. This is critical because: JavaScript frameworks typically caution against using clustered templates Form logic now lies in the component class Essentially, Angular reactive forms give developers more control because every decision related to inputs and controls must be intentional and explicit. To [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Reactive forms in Angular enable you to build clean forms without using too many directives. This is critical because:</p>



<ul>
<li>JavaScript frameworks typically caution against using clustered templates</li>
<li>Form logic now lies in the component class</li>
</ul>



<p>Essentially, <a href="https://angular.io/guide/reactive-forms" target="_blank" rel="noreferrer noopener">Angular reactive forms</a> give developers more control because every decision related to inputs and controls must be intentional and explicit.</p>



<p>To ensure the quality of your data, it’s always a good practice to <a href="https://angular.io/guide/form-validation" target="_blank" rel="noreferrer noopener">validate reactive form input</a> for accuracy and completeness. In this tutorial, we’ll show you how to validate reactive forms in Angular using <code>FormBuilder</code>.</p>



<p>To follow along, make sure you have the latest versions of <a href="https://nodejs.org/en/" target="_blank" rel="noreferrer noopener">Node.js (15.5.0)</a> and <a href="https://github.com/angular/angular" target="_blank" rel="noreferrer noopener">Angular (11.0.5)</a> installed, along with the <a href="https://github.com/angular/angular-cli/releases" target="_blank" rel="noreferrer noopener">Angular CLI (11.0.5)</a>. You can download the starter project on <a href="https://github.com/viclotana/ng-group" target="_blank" rel="noreferrer noopener">GitHub</a>.</p>



<h2 class="wp-block-heading" id="formcontrolsandformgroupsinangular">Form controls and form groups in Angular</h2>



<p>Form controls are classes that can hold both the data values and the validation information of any form element, which means every form input you have in a reactive form should be bound by a form control. These are the basic units that make up reactive forms.</p>



<p><code>FormControl</code> is a class in Angular that tracks the value and validation status of an individual form control. One of the three essential building blocks in Angular forms — along with <code>FormGroup</code> and <code>FormArray</code> — <code>FormControl</code> extends the <code>AbstractControl</code> class, which enables it to access the value, validation status, user interactions, and events.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<p>Form groups are constructs that basically wrap a collection of form controls. Just as the control gives you access to the state of an element, the group gives the same access, but to the state of the wrapped controls. Every single form control in the form group is identified by name when initializing.</p>



<p><code>FormGroup</code> is used with <code>FormControl</code> to track the value and validate the state of form control. In practice,  <code>FormGroup</code> aggregates the values of each child <code>FormControl</code> into a single object, using each control name as the key. It calculates its status by reducing the status values of its children so that if one control in a group is invalid, the entire group is rendered invalid.</p>



<h2 class="wp-block-heading" id="whatisformvalidationinangular">What is form validation in Angular?</h2>



<p>Form validation in Angular enables you to verify that the input is accurate and complete. You can validate user input from the UI and display helpful validation messages in both template-driven and reactive forms.</p>



<p>When validating reactive forms in Angular, validator functions are added directly to the form control model in the component class. Angular calls these functions whenever the value of the control changes.</p>



<p>Validator functions can be either synchronous or asynchronous:</p>



<ul>
<li>Synchronous validators take a control instance and return either a set of errors or null. When you create a <code>FormControl</code>, you can pass sync functions in as the second argument.</li>
<li>Asynchronous validators take a control instance and return a Promise or an Observable that later issues either a set of errors or null. You can pass async functions in as the third argument when you instantiate a <code>FormControl</code>.</li>
</ul>



<p>Depending on the unique needs and goals of your project, you may choose to either <a href="https://angular.io/guide/form-validation#validating-input-in-reactive-forms" target="_blank" rel="noreferrer noopener">write custom validator functions</a> or use any of Angular’s <a href="https://angular.io/api/forms/Validators" target="_blank" rel="noreferrer noopener">built-in validators</a>.</p>



<p>Without further ado, let’s get started building reactive forms.</p>



<h2 class="wp-block-heading" id="whatisformbuilder">What is <code>FormBuilder</code>?</h2>



<p>Setting up form controls, especially for very long forms, can quickly become both monotonous and stressful. <code>FormBuilder</code> in Angular helps you streamline the process of building complex forms while avoiding repetition.</p>



<p>Put simply, <code>FormBuilder</code> provides syntactic sugar that eases the burden of creating instances of <code>FormControl</code>, <code>FormGroup</code>, or <code>FormArray</code> and reduces the amount of boilerplate required to build complex forms.</p>



<h2 class="wp-block-heading" id="howtouseformbuilder">How to use <code>FormBuilder</code></h2>



<p>The example below shows how to build a reactive form in Angular using <code>FormBuilder</code>.</p>



<p>You should have downloaded and opened the <a href="https://github.com/viclotana/ng-group">starter project</a> in VS Code. If you open the <code>employee.component.ts</code>, file it should look like this:</p>



<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl(''),
    stackDetails: new FormGroup({
      stack: new FormControl(''),
      experience: new FormControl('')
    }),
    address: new FormGroup({
        country: new FormControl(''),
        city: new FormControl('')
    })
  });
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}</code></pre>



<p>You can see that every single form control — and even the form group that partitions it — is spelled out, so over time, you end up repeating yourself. <code>FormBuilder</code> helps solve this efficiency problem.</p>



<h3 class="wp-block-heading" id="registeringformbuilder">Registering <code>FormBuilder</code></h3>



<p>To use <code>FormBuilder</code>, you must first register it. To register <code>FormBuilder</code> in a component, import it from Angular forms:</p>



<pre class="wp-block-code"><code>import { FormBuilder } from ‘@angular/forms’;</code></pre>



<p>The next step is to inject the form builder service, which is an injectable provider that comes with the reactive forms module. You can then use the form builder after injecting it. Navigate to the <code>employee.component.ts</code> file and copy in the code block below.</p>



<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = this.fb.group({
    firstName: [''],
    lastName: [''],
    age: [''],
    stackDetails: this.fb.group({
      stack: [''],
      experience: ['']
    }),
    address: this.fb.group({
        country: [''],
        city: ['']
    })
  });
constructor(private fb: FormBuilder) { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}</code></pre>



<p>This does exactly the same thing as the previous code block you saw at the start, but you can see there is a lot less code and more structure — and, thus, optimal usage of resources. Form builders not only help to make your reactive forms’ code efficient, but they are also important for form validation.</p>



<h2 class="wp-block-heading" id="howtovalidateformsinangular">How to validate forms in Angular</h2>



<p>Using reactive forms in Angular, you can validate your forms inside the form builders.</p>



<p>Run your application in development with the command:</p>



<pre class="wp-block-code"><code>ng serve</code></pre>



<p>You will discover that the form submits even when you do not input values into the text boxes. This can easily be checked with form validators in reactive forms. The first thing to do, as with all elements of reactive forms, is to import it from Angular forms.</p>



<pre class="wp-block-code"><code>import { Validators } from '@angular/forms';</code></pre>



<p>You can now play around with the validators by specifying the form controls that must be filled in order for the submit button to be active. Copy the code block below into the <code>employee.component.ts</code> file:</p>



<p>The last thing to do is to make sure the submit button’s active settings are set accordingly. Navigate to the <code>employee.component.html</code> file and make sure the submit statement looks like this:</p>



<pre class="wp-block-code"><code>&lt;button type=”submit” [disabled]=”!bioSection.valid”&gt;Submit Application&lt;/button&gt;</code></pre>



<p>If you run your application now, you will see that if you do not set an input for first name, you cannot submit the form — isn’t that cool?</p>



<h3 class="wp-block-heading" id="displayinginputvaluesandstatus">Displaying input values and status</h3>



<p>Let’s say you want to use the value and status properties to display, in real-time, the input values of your reactive form and whether it can be submitted or not.</p>



<p>The reactive forms API lets you use the value and status properties on your form group or form controls in the template section. Open your <code>employee.component.html</code> file and copy in the code block below:</p>



<pre class="wp-block-code"><code>&lt;form [formGroup]="bioSection" (ngSubmit)="callingFunction()"&gt;
    &lt;h3&gt;Bio Details
&lt;/h3&gt;

  &lt;label&gt;
    First Name:
    &lt;input type="text" formControlName="firstName"&gt;
  &lt;/label&gt; &lt;br&gt;
&lt;label&gt;
    Last Name:
    &lt;input type="text" formControlName="lastName"&gt;
  &lt;/label&gt; &lt;br&gt;
&lt;label&gt;
    Age:
    &lt;input type="text" formControlName="age"&gt;
  &lt;/label&gt;
&lt;div formGroupName="stackDetails"&gt;
    &lt;h3&gt;Stack Details&lt;/h3&gt;

    &lt;label&gt;
      Stack:
      &lt;input type="text" formControlName="stack"&gt;
    &lt;/label&gt; &lt;br&gt;

    &lt;label&gt;
      Experience:
      &lt;input type="text" formControlName="experience"&gt;
    &lt;/label&gt;
  &lt;/div&gt;
&lt;div formGroupName="address"&gt;
    &lt;h3&gt;Address&lt;/h3&gt;

    &lt;label&gt;
      Country:
      &lt;input type="text" formControlName="country"&gt;
    &lt;/label&gt; &lt;br&gt;

    &lt;label&gt;
      City:
      &lt;input type="text" formControlName="city"&gt;
    &lt;/label&gt;
  &lt;/div&gt;
&lt;button type="submit" [disabled]="!bioSection.valid"&gt;Submit Application&lt;/button&gt;
  &lt;p&gt;
    Real-time data: {{ bioSection.value | json }}
  &lt;/p&gt;
  &lt;p&gt;
    Your form status is : {{ bioSection.status }}
  &lt;/p&gt;
&lt;/form&gt;</code></pre>



<p>This displays both the value and the status for submission for you in the interface as you use the form. The complete code to this tutorial can be <a href="https://github.com/viclotana/ng-group">found here on GitHub</a>.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>This article gives an overview of the form builder and how it is a great efficiency enabler for form controls and form groups. It also shows how important it can be for handling form validation easily with reactive forms.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/angular-tips-build-clean-forms-using-reactive-forms/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Angular InjectionToken Feature</title>
		<link>https://topreviewhostingasp.net/angular-injectiontoken-feature/</link>
					<comments>https://topreviewhostingasp.net/angular-injectiontoken-feature/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 19 Aug 2022 04:21:33 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular injection token]]></category>
		<category><![CDATA[angular injection token feature]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[angular tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3139</guid>

					<description><![CDATA[In this article, I want to talk about a feature which Angular provides, that isn’t particularly well known or used by many developers. When using Angular InjectionToken, we can specify a factory function which returns a default value of the parameterized type T. For example: This sets up the InjectionToken using this factory as a provider, as if it was defined [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, I want to talk about a feature which Angular provides, that isn’t particularly well known or used by many developers. When using Angular <code>InjectionToken</code>, we can specify a <strong>factory</strong> function which returns a default value of the parameterized type <code>T</code>. For example:</p>



<pre class="wp-block-code"><code>const WINDOW = new InjectionToken&lt;Window&gt;('A reference to the window object', {
  factory: () =&gt; window,
});</code></pre>



<p>This sets up the <code><a href="https://angular.io/api/core/InjectionToken" target="_blank" rel="noreferrer noopener">InjectionToken</a></code> using this factory as a provider, as if it was defined explicitly in the application’s root injector. Now we can use it anywhere in our application:</p>



<pre class="wp-block-code"><code>@Component({
  selector: 'my-app'
})
export class AppComponent {
  constructor(@Inject(WINDOW) window: Window) {}
}</code></pre>



<p>But that’s not all. We can use the <code><a href="https://angular.io/api/core/inject#inject" target="_blank" rel="noreferrer noopener">inject</a></code> function to obtain a reference to other providers inside our <code>factory</code> function. Let’s see another real-world example:</p>



<pre class="wp-block-code"><code>import { inject, InjectionToken } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

export type TimespanProvider = Observable&lt;string&gt;;

export const TIMESPAN = new InjectionToken('Subscribe to timespan query param', {
  factory() {
    const activatedRoute = inject(ActivatedRoute);

    return activatedRoute.queryParams.pipe(
      pluck('timespan'),
      filterNil(),
      distinctUntilChanged()
    );
  },
});</code></pre>



<p>In the above example, we inject the <code>ActivatedRoute</code> provider and return an observable for the <code>timespan</code> query param. Now we can use it in our components:</p>



<pre class="wp-block-code"><code>@Component({
  selector: 'app-home'
})
export class HomeComponent implements OnInit {
  constructor(@Inject(TIMESPAN) private timespan$: TimespanProvider) {}

  ngOnInit() {
    this.timespan$.pipe(untilDestroyed(this)).subscribe(console.log);
  }
}</code></pre>



<p>We can also pass <code>InjectionFlags</code> to the inject function. For example, we can say that the requested provider is <code>optional</code>:</p>



<pre class="wp-block-code"><code>import { inject, InjectionToken, InjectFlags } from '@angular/core';

const MY_PROVIDER = new InjectionToken('', {
  factory: () =&gt; {
    const optional = inject(SomeProvider, InjectFlags.Optional);
    
    return optional ?? fallback;
  },
});</code></pre>



<p>Here’s another real-world example — let’s say you have a theme service, which exposes the current user’s theme:</p>



<pre class="wp-block-code"><code>@Injectable({ providedIn: 'root' })
export class ThemeService {
  private theme = new Subject&lt;string&gt;();
  theme$ = this.theme.asObservable();

  setTheme(theme: string) {
    this.theme.next(theme);
  }
}</code></pre>



<p>The only data that most components need is the current theme. So instead of doing the following in each component:</p>



<pre class="wp-block-code"><code>@Component({
  selector: 'app-hello',
  template: `&lt;h1&gt;{{ theme$ | async }}&lt;/h1&gt;`
})
export class HelloComponent {
  theme$: Observable&lt;string&gt;;

  constructor(private themeService: ThemeService) {}

  ngOnInit() {
    this.theme$ = this.themeService.theme$;
  } 

}</code></pre>



<p>We can create a provider with the sole purpose of providing the current user’s theme:</p>



<pre class="wp-block-code"><code>export type ActiveThemeProvider = Observable&lt;string&gt;;
export const ACTIVE_THEME = new InjectionToken&lt;ActiveThemeProvider&gt;('Active theme', {
  factory() {
    return inject(ThemeService).theme$;
  }
});</code></pre>



<pre class="wp-block-code"><code>@Component({
  template: `&lt;h1&gt;{{ theme$ | async }}&lt;/h1&gt;`
})
export class HelloComponent {
  constructor(@Inject(ACTIVE_THEME) public theme$: ActiveThemeProvider) {}
}</code></pre>



<p id="03aa">In summary, the benefits of using the <code>InjectionToken</code> factory function are:</p>



<ul>
<li>The provider is tree-shakeable, since we don’t need to inject it in our app module as we’d do with the <code>useFactory</code> provider.</li>
<li>Using <code>inject()</code> to request a provider is faster and more type-safe than providing an additional array of dependencies (which is the common usage of <code>useFactory</code> providers).</li>
<li>The provider has a single responsibility, and our components are injected only with the data they need.</li>
<li>It makes testing more straightforward because we don’t need to mock everything. We can return a mock value from the factory, and that’s all.</li>
</ul>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/angular-injectiontoken-feature/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Combine ASP.NET Core SignalR Chat with Angular 5</title>
		<link>https://topreviewhostingasp.net/how-to-combine-asp-net-core-signalr-chat-with-angular-5/</link>
					<comments>https://topreviewhostingasp.net/how-to-combine-asp-net-core-signalr-chat-with-angular-5/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 23 Apr 2021 07:39:28 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular 5]]></category>
		<category><![CDATA[angular 5 tutorial]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[signalr]]></category>
		<category><![CDATA[signalr tips]]></category>
		<category><![CDATA[signalr tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2952</guid>

					<description><![CDATA[In this post, I will show an article how to use command line prompt with dotnet CLI and Angular CLI. Let&#8217;s get started. Create the Projects We will create a new empty ASP.NET Core Web project. You can either do it with Visual Studio or execute dotnet new web in the command line. I have Angular CLI installed on [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this post, I will show an article how to use command line prompt with dotnet CLI and Angular CLI. Let&#8217;s get started.</p>



<h2 class="wp-block-heading">Create the Projects</h2>



<p>We will create a new empty ASP.NET Core Web project. You can either do it with Visual Studio or execute<strong><em> dotnet new web</em></strong> in the command line.</p>



<p>I have Angular CLI installed on my machine. If you don’t either install it or create a new empty Angular application. I am using Angular CLI 1.5 and creating a new project with it – Angular 5 application.</p>



<p>I will just execute <em><strong>ng new CodingBlastChat </strong></em>in the command line, inside of solution folder. And now I have basic working Angular application. To start it, I just type in <em><strong>ng serve</strong></em> and I my application is running on <em>localhost</em> port <em>4200.</em></p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com"><img loading="lazy" decoding="async" width="300" height="271" class="wp-image-2953 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<h2 class="wp-block-heading">Installing dependencies</h2>



<p>We need to install both server-side and client-side libraries for ASP.NET Core SignalR.</p>



<p>To install the server-side library we will use NuGet. You can either use Visual Studio or do it via command line. The package name is <em>Microsoft.AspNetCore.SignalR</em></p>



<p><strong><em>dotnet add package Microsoft.AspNetCore.SignalR</em></strong></p>



<p>We will use npm to add client-side library:</p>



<p><strong><em>npm install @aspnet/</em>signalr<em>-client</em></strong></p>



<p>If you are using npm 4 or older you will need to add the<em> –save</em> argument, if you want it to be saved inside of your package.json as well. And that’s it for library dependencies. We are all set and we can now use SignalR.</p>



<h2 class="wp-block-heading">Setting up server-side</h2>



<p>We can now add the simple ChatHub class:</p>



<pre class="wp-block-code"><code>public class ChatHub : Hub
{
    public void SendToAll(string name, string message)
    {
        Clients.All.InvokeAsync("sendToAll", name, message);
    }
} </code></pre>



<p>This will call the <em>sendToAll </em>client method for ALL clients.</p>



<p>For SignalR to work we have to add it to DI Container inside of <em>ConfigureServices</em> method in Startup class:</p>



<pre class="wp-block-code"><code>services.AddSignalR();
</code></pre>



<p>Also, we have to tell the middleware pipeline that we will be using SignalR. When the request comes to the <em>/chat</em> endpoint we want our ChatHub to take over and handle it.</p>



<pre class="wp-block-code"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSignalR(routes =&gt;
    {
        routes.MapHub&lt;ChatHub&gt;("chat");
    });
} </code></pre>



<h2 class="wp-block-heading">Enabling CORS</h2>



<p>Since we will be serving the Angular application on a separate port, for it to be able to access the SignalR server we will need to enable CORS on the Server.</p>



<p>Add the following inside of <em>ConfigureServices</em>, just before the code that adds SignalR to DI container.</p>



<pre class="wp-block-code"><code>services.AddCors(o =&gt; o.AddPolicy("CorsPolicy", builder =&gt;
    {
        builder
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithOrigins("http://localhost:4200");
    }));</code></pre>



<p>We also have to tell the middleware to use this CORS policy. Add the following inside of Configure method, BEFORE SignalR:</p>



<pre class="wp-block-code"><code>app.UseCors("CorsPolicy");
</code></pre>



<p>Now your Configure method should look like this:</p>



<pre class="wp-block-code"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("CorsPolicy");

    app.UseSignalR(routes =&gt;
    {
        routes.MapHub&lt;ChatHub&gt;("chat");
    });
}</code></pre>



<p>Also, make sure to check your Properties/launchSettings.json file so you can know which port is your app running. You can also configure it to use any port you want. I will set it to 5000.</p>



<h2 class="wp-block-heading">Client-side</h2>



<p>You would ideally want to have a separate service for communicating with ChatHub on the server. Also, you would want to store your endpoints in some kind of Angular service for constants. But for the simplicity sake, we will skip that for now and add it after we make the chat functional.</p>



<p>I will use existing <em>AppComponent</em> that Angular CLI created, and extend it.</p>



<p>I will add properties for nick, message and list of messages. Also, I will add a property for <em>HubConnection</em>.</p>



<pre class="wp-block-code"><code>import { Component } from '@angular/core';
import { HubConnection } from '@aspnet/signalr-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private hubConnection: HubConnection;
  nick = '';
  message = '';
  messages: string[] = [];
}</code></pre>



<p>HubConnection is part of the signalr-client library built by ASP.NET team. And we will use it to establish the connection with the server and also to send messages and listen for messages from the server.</p>



<p>We will establish the connection before any other code runs in our component. Hence, we will use the OnInit event.</p>



<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private hubConnection: HubConnection;
  nick = '';
  message = '';
  messages: string[] = [];

  ngOnInit() {
    this.nick = window.prompt('Your name:', 'John');

    this.hubConnection = new HubConnection('http://localhost:5000/chat');

    this.hubConnection
      .start()
      .then(() =&gt; console.log('Connection started!'))
      .catch(err =&gt; console.log('Error while establishing connection :('));

    }
}</code></pre>



<p>Notice the ngOnInit method. We are asking the user to enter his name and we store that inside of nick property that we created previously.</p>



<p>After that, we create the HubConnection object and try to establish the connection with the server.</p>



<p>Inside of that method, we will also add the listener for <em>sendToAll</em> event from the server:</p>



<pre class="wp-block-code"><code>this.hubConnection.on('sendToAll', (nick: string, receivedMessage: string) =&gt; {
  const text = `${nick}: ${receivedMessage}`;
  this.messages.push(text);
});</code></pre>



<p>After the event is received, we get two parameters: <em>nick</em> and the <em>message</em> itself. Now we form the new string from these two parameters and we add it to our <em>messages</em> array on AppComponent.</p>



<p>Inside of AppComponent we also need a method for sending messages from client TO server. We will use it from our view and here is the code:</p>



<pre class="wp-block-code"><code>  public sendMessage(): void {
    this.hubConnection
      .invoke('sendToAll', this.nick, this.message)
      .catch(err =&gt; console.error(err));
  }</code></pre>



<h2 class="wp-block-heading">View</h2>



<p>Now we need to set up the view. Since we plan to use the form element, we will import FormsModule in our AppModule. We will change the <em>app.module.ts</em> file.</p>



<p>We can now add the view to app.component.html:</p>



<pre class="wp-block-code"><code>&lt;div id="main-container" style="text-align:center"&gt;
  &lt;h1&gt;
    &lt;a href="https://codingblast.com/asp-net-core-signalr-simple-chat/" target="_new"&gt;
      ASP.NET Core SignalR Chat with Angular
    &lt;/a&gt;
  &lt;/h1&gt;

  &lt;div class="container"&gt;
    &lt;h2&gt;Hello {{nick}}!&lt;/h2&gt;
    &lt;form (ngSubmit)="sendMessage()" #chatForm="ngForm"&gt;
      &lt;div&gt;
        &lt;label for="message"&gt;Message&lt;/label&gt;
        &lt;input type="text" id="message" name="message" [(ngModel)]="message" required&gt;
      &lt;/div&gt;
      &lt;button type="submit" id="sendmessage" [disabled]="!chatForm.valid"&gt;
        Send
      &lt;/button&gt;
    &lt;/form&gt;
  &lt;/div&gt;

  &lt;div class="container" *ngIf="messages.length &gt; 0"&gt;
    &lt;div *ngFor="let message of messages"&gt;
      &lt;span&gt;{{message}}&lt;/span&gt;
    &lt;/div&gt;
  &lt;/div&gt;

&lt;/div&gt;</code></pre>



<p>The view has two main parts. First is a container for sending messages with a form that consists of input and button for sending the message. The second part is for listing the messages that we store inside of <em>messages</em> property on <em>AppComponent</em>. We push a new message to this array every time we get an event (message) from the ASP.NET Core SignalR server. That’s all there is to it!</p>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-combine-asp-net-core-signalr-chat-with-angular-5/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
