<?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 tutorial &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/angular-tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Thu, 10 Aug 2023 03:55:45 +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 tutorial &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 fetchpriority="high" 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 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>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 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>
