<?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 &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/angular/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Mon, 22 Jul 2024 04:50:07 +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 &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Add Attachments to Adobe Using C#</title>
		<link>https://topreviewhostingasp.net/how-to-add-attachments-to-adobe-using-c/</link>
					<comments>https://topreviewhostingasp.net/how-to-add-attachments-to-adobe-using-c/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Mon, 22 Jul 2024 04:11:52 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[adobe c#]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3867</guid>

					<description><![CDATA[PDF/A-3 supports the embedding of any file type into PDF documents. This enables the transition from electronic paper to an electronic container that stores both the human and machine-readable versions of a document. Applications can extract the machine-readable portion of a PDF document and process it. A PDF/A-3 document can include an unlimited number of [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>PDF/A-3 supports the embedding of any file type into PDF documents. This enables the transition from electronic paper to an electronic container that stores both the human and machine-readable versions of a document. Applications can extract the machine-readable portion of a PDF document and process it. A PDF/A-3 document can include an unlimited number of embedded documents for various processes.</p>
<p>This article will teach you how to embed a plain text file in a PDF document and how to extract the attachment from it.</p>
<h2 id="adding-attachments" data-nav="true">Adding Attachments</h2>
<p>This sample code demonstrates how TX Text Control can be used to attach a text file to a PDF document.</p>
<pre>        // create a non-UI ServerTextControl instance
using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) {

  tx.Create();
  // set dummy content
  tx.Text = "PDF Document Content";

  // read the content of the attachment
  string sAttachment = System.IO.File.ReadAllText("attachment.txt");

  // create the attachement
  TXTextControl.EmbeddedFile attachment =
     new TXTextControl.EmbeddedFile(
        "attachment.txt",
        sAttachment,
        null) {
       Description = "My Text File",
       Relationship = "Unspecified",
       MIMEType = "application/txt",
       CreationDate = DateTime.Now,
     };

  // attached the embedded file
  tx.DocumentSettings.EmbeddedFiles =
     new TXTextControl.EmbeddedFile[] { attachment };

  // save as PDF/A
  tx.Save("document.pdf", TXTextControl.StreamType.AdobePDFA);
}</pre>
<p>The attached file is represented by the EmbeddedFile object. The constructor accepts the file name, data, and additional meta data. In addition, the MIME type of the attachment (application/text in this case), a textual description, a relationship, and the creation date are provided.</p>
<p>The relationship is an optional string that describes the relationship between the embedded file and the containing document. It can be a predefined value or adhere to the rules for second-class names (ISO 32000-1, Annex E). Predefined values include <strong>&#8220;Source&#8221;</strong>, <strong>&#8220;Data&#8221;</strong>, <strong>&#8220;Alternative&#8221;</strong>, <strong>&#8220;Supplement&#8221;</strong>, and <strong>&#8220;Unspecified&#8221;</strong>.</p>
<p>When you open the document in Adobe Acrobat Reader, the attachment will appear in the Attachments side panel.</p>
<p><img fetchpriority="high" decoding="async" class="size-full wp-image-3868 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2024/07/attachment.webp" alt="" width="988" height="724" srcset="https://topreviewhostingasp.net/wp-content/uploads/2024/07/attachment.webp 988w, https://topreviewhostingasp.net/wp-content/uploads/2024/07/attachment-300x220.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2024/07/attachment-768x563.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2024/07/attachment-50x37.webp 50w" sizes="(max-width: 988px) 100vw, 988px" /></p>
<h2 id="extracting-attachments" data-nav="true">Extracting Attachments</h2>
<p>The code below loads the created PDF file in order to locate the attachment by looping through all embedded files. The found attachment is extracted and saved as a text file.</p>
<pre>// create a non-UI ServerTextControl instance
using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) {

  tx.Create();

  // load the PDF document
  TXTextControl.LoadSettings ls = new TXTextControl.LoadSettings();
  tx.Load("document.pdf", TXTextControl.StreamType.AdobePDF, ls);

  // read the attachments
  TXTextControl.EmbeddedFile[] files = ls.EmbeddedFiles;

  // find the specific attachment and save it
  foreach(TXTextControl.EmbeddedFile file in files) {
    if (file.Description == "My Text File") {
      string sAttachment = Encoding.UTF8.GetString((byte[])file.Data);
      System.IO.File.WriteAllText("attachment_read.txt", sAttachment);

      break;
    }
  }
}</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-add-attachments-to-adobe-using-c/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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 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 loading="lazy" 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>
	</channel>
</rss>
