<?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 5 &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/angular-5/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Tue, 10 Jul 2018 07:39:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Angular 5 &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Validation Using Template Driven Forms in Angular 5</title>
		<link>https://mail.sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/</link>
					<comments>https://mail.sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 22 Apr 2018 15:58:46 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[How to]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[ng5]]></category>
		<category><![CDATA[Template Driven Forms]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12798</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how to do validation using template driven forms in Angular 5, this is just a different approach that you can follow, as we have discussed another way in our previous post. At the end of this article, you will get to know how you can implement validations in Angular 5 application using Template Driven Forms. This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post, we are going to see how to do validation using template driven forms in <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5, this is just a different approach that you can follow, as we have discussed another way in our previous post. At the end of this article, you will get to know how you can implement validations in Angular 5 application using <em>Template Driven Forms.</em> This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>Validations have a vital role in all application no matter in what language it is been developed. And since it is an essential part, there are many ways to achieve it. We are going to see Template Driven Forms approach here.</p>
<h2>Using the code</h2>
<p style="text-align: left;">It is recommended to clone the project from GitHub, so that you can try everything your own. Let&#8217;s go ahead and write some codes now.</p>
<h3>Install Bootstrap</h3>
<p>Before we begin, let&#8217;s install bootstrap in our application.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\My Projects\ng5&gt; npm install bootstrap --save</pre>
<p>As we are developing this application using Angular CLI, we can add the reference of Bootstrap in our Angular-CLI.json file. The styles section of that file will look like below after you add the reference.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"styles": [
        "styles.css",
        "../node_modules/bootstrap/dist/css/bootstrap.min.css"
      ]</pre>
<p>Please be noted that there are many other ways to configure Bootstrap in our application, here we are not going to explain that.</p>
<h3>Importing ngForm to a variable</h3>
<p>Let&#8217;s clean codes in our Registration component and add a new form which has a form variable, and this form variable can hold the values of our form. There are many things you can do with this variable, for now, let&#8217;s say it is our model values container.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container"&gt;
  &lt;div class="row"&gt;
    &lt;div class="no-float center-block col-lg-4 col-sm-4"&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Sign up&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;form #regsiterForm="ngForm" (ngSubmit)="register(regsiterForm)"&gt;
          &lt;/form&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { OnInit, Component } from "@angular/core";

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  constructor() {
  }

  ngOnInit() {
  }
}


</pre>
<h3>Implement Validation for User Name field using Template Driven Forms</h3>
<p>As we have created our form, now it is time to generate out input controls into it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;form #regsiterForm="ngForm" (ngSubmit)="register(regsiterForm)"&gt;
    &lt;div class="signup-fields"&gt;
        &lt;div class="form-group"&gt;
            &lt;input type="text" required name="userName" class="form-control" placeholder="User Name"&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;button class="btn btn-primary btn-block" type="submit"&gt;Signup&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt;</pre>
<p>What we have above is a simple HTML with template driven form, where we are going to introduce the validation. Let&#8217;s modify the userName field now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;input type="text" [(ngModel)]="userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;</pre>
<p>What we are trying to achieve by the above code is, creating a reference variable userName and assign the input value to it. Basically, this is a two-way binding, where we can set the data from our component and update it in the form, and vice versa. Now if you run your application, you should see an error as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">Uncaught Error: Cannot assign to a reference or variable!
    at _AstToIrVisitor.visitPropertyWrite (compiler.js:26025)
    at PropertyWrite.visit (compiler.js:4585)
    at convertActionBinding (compiler.js:25475)
    at eval (compiler.js:27987)
    at Array.forEach (&lt;anonymous&gt;)
    at ViewBuilder._createElementHandleEventFn (compiler.js:27983)
    at nodes.(anonymous function) (webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:27620:27)
    at eval (compiler.js:27928)
    at Array.map (&lt;anonymous&gt;)
    at ViewBuilder._createNodeExpressions (compiler.js:27927)</pre>
<p>This is because we are using the same name for both model and reference variable. So we should change it. To do so, let&#8217;s create a User Model (user.model.ts) and reference it to our Register component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">export class User {
    id: any;
    userName: string;
    email: string;
    userRole: string;
    profileImage: string;
    phoneNumber: string;
    firstName: string;
    lastName: string;
}</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { User } from '../models/user.model'</pre>
<p>Now we can change our input as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;</pre>
<p>Please make sure that to declare a user in registration component.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">export class RegistrationComponent implements OnInit {
  user = new User();
  constructor() {
  }

  ngOnInit() {
  }
}
</pre>
<p>Now if you run your application, you can see that the Submit button will be enabled only if the form is valid, that is, only if you enter any values in the username field.</p>
<h3>Decorate the validation message</h3>
<p>Now we know that our form is working fine, but don&#8217;t we need to give a message to the users if they haven&#8217;t given any values in the fields? Let&#8217;s add few more markups in our HTML.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="userName.invalid" [class.has-success]="userName.valid"&gt;
    &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
    &lt;span class="help-block" *ngIf="userName.errors?.required"&gt;
                  User Name is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>We are enabling the class &#8220;has-error&#8221; and &#8220;has-success&#8221; dynamically by checking the valid and invalid property of userName field. We are also showing our required field message in a new span if there are any required errors in our userName model. Now if you run your app, you can see that the validation is working fine.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg"><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-12799" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg" alt="" width="455" height="299" srcset="/wp-content/uploads/2018/04/userName-validation-without-touch-property.jpg 455w, /wp-content/uploads/2018/04/userName-validation-without-touch-property-300x197.jpg 300w, /wp-content/uploads/2018/04/userName-validation-without-touch-property-400x263.jpg 400w" sizes="(max-width: 455px) 100vw, 455px" /></a></p>
<p>But isn&#8217;t that validation showing by default, we should show the message only if the user touched our field, and refused to type anything right? Let&#8217;s add &#8220;userName.touched&#8221; in our markup.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="userName.invalid &amp;&amp; userName.touched" [class.has-success]="userName.valid"&gt;
    &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
    &lt;span class="help-block" *ngIf="userName.errors?.required &amp;&amp; userName.touched"&gt;
                  User Name is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<h3>Implement the validation for other fields as well</h3>
<p>Now it is time to implement the same in other fields.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="container" style="margin-top:100px;"&gt;
  &lt;div class="row justify-content-center align-items-center"&gt;
    &lt;div class="col-lg-4 col-sm-4 center-block "&gt;
      &lt;mat-card&gt;
        &lt;mat-card-header&gt;
          &lt;img mat-card-avatar src="../../../assets/images/App-login-manager-icon.png"&gt;
          &lt;mat-card-title&gt;Sign up&lt;/mat-card-title&gt;
          &lt;mat-card-subtitle&gt;Trust us for your data, and sign up&lt;/mat-card-subtitle&gt;
        &lt;/mat-card-header&gt;
        &lt;mat-card-content&gt;
          &lt;form #regsiterForm="ngForm" (ngSubmit)="register(user)"&gt;
            &lt;div class="signup-fields"&gt;
              &lt;div class="form-group" [class.has-error]="userName.invalid &amp;&amp; userName.touched" [class.has-success]="userName.valid"&gt;
                &lt;input type="text" [(ngModel)]="user.userName" #userName="ngModel" required name="userName" class="form-control" placeholder="User Name"&gt;
                &lt;span class="help-block" *ngIf="userName.errors?.required &amp;&amp; userName.touched"&gt;
                  User Name is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="email.invalid &amp;&amp; email.touched" [class.has-success]="email.valid"&gt;
                &lt;input type="text" required [email]="user.email !== ''" [(ngModel)]="user.email" name="email" class="form-control" placeholder="Email"
                  #email="ngModel"&gt;
                &lt;span class="help-block" *ngIf="email.errors?.required &amp;&amp; email.touched"&gt;
                  Email is required
                &lt;/span&gt;
                &lt;span class="help-block" *ngIf="email.errors?.email &amp;&amp; email.touched"&gt;
                  Email is invalid
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="password.invalid &amp;&amp; password.touched" [class.has-success]="password.valid"&gt;
                &lt;input type="password" [(ngModel)]="user.password" required class="form-control" name="password" placeholder="Password" #password="ngModel"&gt;
                &lt;span class="help-block" *ngIf="password.invalid &amp;&amp; password.touched"&gt;
                  Password is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
                &lt;input type="password" required class="form-control" name="confirmPassword" placeholder="Confirm Password" [(ngModel)]="confirmPassword"
                  #confirmPasswordControl="ngModel"&gt;
                &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
              &lt;/div&gt;
              &lt;div&gt;
                &lt;button class="btn btn-primary btn-block" type="submit" [disabled]="regsiterForm.invalid"&gt;Signup&lt;/button&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/form&gt;
        &lt;/mat-card-content&gt;
      &lt;/mat-card&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>For email validation, we have given an additional attribute and set the condition as [email]=&#8221;user.email !== &#8221;&#8221;, this is for not showing both the required validation and email validation together. This will show the required message if the user touched the field and not giving any values, and the email validation will get fired only if the entered value is not a valid email. Sounds good?</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg"><img decoding="async" class="alignnone size-full wp-image-12800" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg" alt="" width="476" height="601" srcset="/wp-content/uploads/2018/04/Template-Driven-Form-Validations.jpg 283w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-238x300.jpg 238w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-400x505.jpg 400w, /wp-content/uploads/2018/04/Template-Driven-Form-Validations-475x600.jpg 475w" sizes="(max-width: 476px) 100vw, 476px" /></a></p>
<h3>Add register function</h3>
<p>Finally, let&#8217;s add our function register.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { OnInit, Component } from "@angular/core";
import { User } from '../models/user.model';
@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
  user = new User();
  constructor() {
  }

  ngOnInit() {
  }

  register(user: User): void{
    console.log(user);
  }
}


</pre>
<p>Once it is done, let&#8217;s open our browser console and see the data.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Console-output.jpg"><img decoding="async" class="alignnone size-full wp-image-12801" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Console-output.jpg" alt="" width="415" height="245" srcset="/wp-content/uploads/2018/04/Console-output.jpg 415w, /wp-content/uploads/2018/04/Console-output-300x177.jpg 300w, /wp-content/uploads/2018/04/Console-output-400x236.jpg 400w" sizes="(max-width: 415px) 100vw, 415px" /></a></p>
<p>Here we have seen how we can implement validation using template driven form. I will write my next article about implementing custom validators using directives in Angular, for comparing our password and confirm password field. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/validation-using-template-driven-forms-in-angular-5/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Implement Shared Custom Validator Directive in Angular</title>
		<link>https://mail.sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/</link>
					<comments>https://mail.sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 22 Apr 2018 15:21:33 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[How to]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[Angular directives]]></category>
		<category><![CDATA[Angular Shared Directive]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12804</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how to create a custom validator directive in Angular 5. We have already seen how to do validation in our previous posts, and we have not done any validations for comparing the password and confirm the password, remember? Here we are going to see that. At the end of this article, you will get to know how to create a new shared directive according to our requirements. This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post, we are going to see how to create a custom validator directive in <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5. We have already seen how to do validation in our previous posts, and we have not done any validations for comparing the password and confirm the password, remember? Here we are going to see that. At the end of this article, you will get to know how to create a new shared directive according to our requirements<em>.</em> This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
<li>Validation Using Template Driven Forms in Angular 5</li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>Validations have a vital role in all application no matter in what language it is been developed. And since it is an essential part, there are many ways to achieve it. If we create a custom shared directive for creating a compare validator, it would be a great piece of code right, which can be reused.</p>
<h2>Using the code</h2>
<p style="text-align: left;">It is recommended to clone the project from GitHub, so that you can try everything your own. Let&#8217;s go ahead and write some codes now.</p>
<h3>Creating a custom directive</h3>
<p>Let&#8217;s just create a new directive in a shared folder and name it <em>equal.validator.directive.ts. </em>Now open that file and start writing the code. Let&#8217;s import some of the core components first.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";</pre>
<p>Now Let&#8217;s define our class and @Directive.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";

@Directive({
    selector: "[appEqualValidator]",
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: EqualValidatorDirective,
        multi: true
    }]
})
export class EqualValidatorDirective implements Validator {
    validate(c: AbstractControl): { [key: string]: any; } {
        throw new Error("Method not implemented.");
    }
    registerOnValidatorChange?(fn: () =&gt; void): void {
        throw new Error("Method not implemented.");
    }
}</pre>
<p>As you can see that, we are actually inheriting our new class  EqualValidatorDirective from Validator. Now we need to change the implementations of the method inside it. We should also add our new directive in app.module.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations'
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule } from '@angular/material';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { EqualValidatorDirective } from './shared/equal.validator.directive';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { NavComponent } from './nav/nav.component';
import { RegistrationComponent } from './registration/registration.component';
import { LoginComponent } from './login/login.component';

import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    NavComponent,
    RegistrationComponent,
    LoginComponent,
    EqualValidatorDirective
  ],
  imports: [
    BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<p>&nbsp;</p>
<h3>Implement validate</h3>
<p>Before we do that, we should add our new cutom directive selector in our confirm password field, because that&#8217;s where we are going to use our validator. So we are going to change our markup for confirm password field as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
    &lt;input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel"&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>As you can see, we are using the selector  <em>appEqualValidator=&#8221;password&#8221; </em>in our confirm password field. Please do check my previous posts if you are not sure how to implement other validations like email and required.</p>
<p>Now let&#8217;s go back to our custom directive and make some changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">export class EqualValidatorDirective implements Validator {
    @Input() appEqualValidator: string;
    validate(c: AbstractControl): { [key: string]: any; } {
        const controlToCompare = c.parent.get(this.appEqualValidator)
        if (controlToCompare &amp;&amp; controlToCompare.value == c.value)return { "equal": true };
        return { "notEqual": true }
    }
    registerOnValidatorChange?(fn: () =&gt; void): void {
        throw new Error("Method not implemented.");
    }
}</pre>
<p>Here, we get our confirmPassword control in the absolute control &#8220;c&#8221;, and in the next line, we are just finding our password control by getting the parent element of confirmPassword. Once we get that, we can easily perform the comparison easily right? So, if it matches we return  { &#8220;equal&#8221;: true }; or else { &#8220;notEqual&#8221;: true }. Sounds good?</p>
<h3>Introduce new span for custom message</h3>
<p>Now we have a custom validator which compares two values, and the only thing which pending is, that to create a span for showing our new message in UI. Let&#8217;s change our markup now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group" [class.has-error]="confirmPasswordControl.invalid &amp;&amp; confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid"&gt;
    &lt;input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel"&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.required &amp;&amp; confirmPasswordControl.touched"&gt;
                  Confirm password is required
                &lt;/span&gt;
    &lt;span class="help-block" *ngIf="confirmPasswordControl.errors?.notEqual 
                      &amp;&amp; confirmPasswordControl.touched &amp;&amp; !confirmPasswordControl.errors?.required"&gt;
                  Password doesn't match
                &lt;/span&gt;
&lt;/div&gt;</pre>
<p>As you can see, we are showing the custom message only if the directive returns notEqual property and there are no required errors. Let&#8217;s run our application and see it in action.</p>
<p><a href="https://sibeeshpassion.com/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg"><img decoding="async" class="alignnone size-full wp-image-12805" src="https://sibeeshpassion.com/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg" alt="" width="384" height="529" srcset="/wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive.jpg 259w, /wp-content/uploads/2018/04/Custom-Shared-Equal-Validator-Directive-218x300.jpg 218w" sizes="(max-width: 384px) 100vw, 384px" /></a></p>
<p>&nbsp;</p>
<p>Here we have seen how we can implement shared custom validator directive. Let&#8217;s connect to a database and save these values in next article. Till then, bye.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/implement-shared-custom-validator-directive-in-angular/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Implementing Guard in Angular 5 App</title>
		<link>https://mail.sibeeshpassion.com/implementing-guard-in-angular-5-app/</link>
					<comments>https://mail.sibeeshpassion.com/implementing-guard-in-angular-5-app/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 26 Mar 2018 09:43:05 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular Auth Guard]]></category>
		<category><![CDATA[Angular Service]]></category>
		<category><![CDATA[Guard in Angular]]></category>
		<category><![CDATA[Implement Login in Angular]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12742</guid>

					<description><![CDATA[[toc] Introduction This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In this post, we are going to implement Guard, which help us to restrict users to access some pages if they haven&#8217;t logged in to our application, in  Angular 5. So at the end of this article, you will get to know how you can handle unauthorized route accesses. I hope you will like this article. Developing an [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In this post, we are going to implement Guard, which help us to restrict users to access some pages if they haven&#8217;t logged in to our application, in  <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5. So at the end of this article, you will get to know how you can handle unauthorized route accesses. I hope you will like this article.</p>
<h2><em>Developing an Angular 5 App</em> series</h2>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implementing-guard-in-angular-5-app">Implementing Guard in Angular 5 App</a></li>
</ol>
<h2><span id="source-code">Source Code</span></h2>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h2>Background</h2>
<p>We may be having many numbers of pages on our app, some may be used by logged in users, and some can be used by unauthorized users. But if you are letting all the users use all the pages, no matter whether they have logged in or not? Yeah, obviously that&#8217;s not a perfect application. In our application, we are going to make our homepage available only for a logged in user. To do this, we can use Guard.</p>
<h2>Using the code</h2>
<p style="text-align: left;">Let&#8217;s go ahead and write some codes now.</p>
<h3>Generate Guard</h3>
<p>As we are using Angular CLI, we can easily generate Auth Guard on our application. Do you remember that we have created some components in our previous article? We can always create a Guard in the same way.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\Visual Studio\ng5&gt; ng generate guard auth</pre>
<p>In the above step, we are generating guard on our root level. Once you run the above command, this will generate two new Typescript files as follows.</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2018/03/Auth-Guard-in-Angular5.jpg"><img decoding="async" class="alignnone wp-image-12743 size-large" src="http://sibeeshpassion.com/wp-content/uploads/2018/03/Auth-Guard-in-Angular5-1024x410.jpg" alt="" width="1024" height="410" srcset="/wp-content/uploads/2018/03/Auth-Guard-in-Angular5-1024x410.jpg 1024w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5-300x120.jpg 300w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5-768x307.jpg 768w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5-400x160.jpg 400w, /wp-content/uploads/2018/03/Auth-Guard-in-Angular5.jpg 634w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Let&#8217;s go to those two files now.</p>
<p><strong>auth.guard.ts</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {
    return true;
  }
}
</pre>
<p><strong>auth.guard.spec.ts</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { TestBed, async, inject } from '@angular/core/testing';

import { AuthGuard } from './auth.guard';

describe('AuthGuard', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [AuthGuard]
    });
  });

  it('should ...', inject([AuthGuard], (guard: AuthGuard) =&gt; {
    expect(guard).toBeTruthy();
  }));
});
</pre>
<p>This is just a test file, we can see how to perform tests on the Angular app in another article. Let&#8217;s concentrate on the implementation for now.</p>
<h3>Generate login component and set up</h3>
<p>Now that we have Guard ready for modification before we do that, let&#8217;s create a component for login.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">PS F:\Visual Studio\ng5&gt; ng g c login
  create src/app/login/login.component.html (24 bytes)
  create src/app/login/login.component.spec.ts (621 bytes)
  create src/app/login/login.component.ts (265 bytes)
  create src/app/login/login.component.css (0 bytes)
  update src/app/app.module.ts (1331 bytes)
PS F:\Visual Studio\ng5&gt;</pre>
<p>Now it is time to edit our routes in app.module.ts with the new route for login. Please be noted that it is not a recommended way to create routes in app.module.ts file. We should create a separate routing module for the same and use it in app.module.ts. I will be sharing how to do that in another article.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { LoginComponent } from './login/login.component';

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' },
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent}]

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    NavComponent,
    RegistrationComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [],
  bootstrap: [AppComponent]
})</pre>
<p>We may also need to edit the nav.component.html by adding a new button for login.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-toolbar color="primary"&gt;
  &lt;button mat-button routerLink="/"&gt;Home&lt;/button&gt;
  &lt;button mat-button routerLink="/register"&gt;Register&lt;/button&gt;
  &lt;button mat-button routerLink="/login"&gt;Login&lt;/button&gt;
&lt;/mat-toolbar&gt;</pre>
<p>Now, go to your login.component.html file and add the following markup.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-card&gt;
  &lt;form [formGroup]="form" (ngSubmit)="login()"&gt;
    &lt;mat-input-container&gt;
      &lt;input matInput type="email" placeholder="Email" formControlName="email" /&gt;
    &lt;/mat-input-container&gt;
    &lt;mat-input-container&gt;
      &lt;input matInput type="password" placeholder="Password" formControlName="password" /&gt;
    &lt;/mat-input-container&gt;
    &lt;button mat-raised-button type="submit" color="primary"&gt;Login&lt;/button&gt;
  &lt;/form&gt;
&lt;/mat-card&gt;</pre>
<p>As you can see, we are actually calling a login method on submit. Before we implement that function now on login.component.ts file let&#8217;s create an auth service and edit as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class AuthService {

  constructor(private myRoute: Router) { }

  sendToken(token: string) {
    localStorage.setItem("LoggedInUser", token)
  }

  getToken() {
    return localStorage.getItem("LoggedInUser")
  }

  isLoggednIn() {
    return this.getToken() !== null;
  }

  logout() {
    localStorage.removeItem("LoggedInUser");
    this.myRoute.navigate(["login"]);
  }


}
</pre>
<p>Now it is time to edit our login.component.ts file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  form;
  constructor(private fb: FormBuilder,
    private myRoute: Router,
    private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

  ngOnInit() {
  }

  login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }

}
</pre>
<blockquote><p>This is not the preferred way of doing this, instead, you should create an API service and connect to a database. And then, check whether this email and password are valid or not, at last, you should set the localStorage with the token you get from server API. This topic is enough for another article, to make this article short, I am just setting the value email here.</p></blockquote>
<p>If you are getting an error as &#8220;ERROR Error: Uncaught (in promise): EmptyError: no elements in sequence&#8221;, please make sure that you have rxjs version greater than or equal to 5.5.4 in package.json file. The rxjs version 5.5.3 has this issue with Angular 5.</p>
<p>Now run your application and make sure that it is redirecting to the homepage. you can also check the localStorage entry on your browser console.</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2018/03/localStorage-entry.jpg"><img decoding="async" class="alignnone wp-image-12744 size-full" src="http://sibeeshpassion.com/wp-content/uploads/2018/03/localStorage-entry.jpg" alt="" width="612" height="356" srcset="/wp-content/uploads/2018/03/localStorage-entry.jpg 612w, /wp-content/uploads/2018/03/localStorage-entry-300x175.jpg 300w, /wp-content/uploads/2018/03/localStorage-entry-400x233.jpg 400w" sizes="(max-width: 612px) 100vw, 612px" /></a></p>
<h3>Set up Guard generated</h3>
<p>Let&#8217;s go to our auth.guard.ts file and make some changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import {Router} from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService,
    private myRoute: Router){

  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {
    if(this.auth.isLoggednIn()){
      return true;
    }else{
      this.myRoute.navigate(["login"]);
      return false;
    }
  }
}
</pre>
<p>Do not forget to add AuthService and AuthGuard in providers in app.module.ts.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';</pre>
<h3>Use Auth Guard in Routes</h3>
<p>Wow, the set up is done, now it is time for action. Let&#8217;s go to our routes now and change the code as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];</pre>
<p>Run your application and try to access the home page before login if everything goes fine, it should redirect you to login page.</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2018/03/Guard-output.jpg"><img decoding="async" class="alignnone size-large wp-image-12746" src="http://sibeeshpassion.com/wp-content/uploads/2018/03/Guard-output-1024x453.jpg" alt="" width="1024" height="453" srcset="/wp-content/uploads/2018/03/Guard-output-1024x453.jpg 1024w, /wp-content/uploads/2018/03/Guard-output-300x133.jpg 300w, /wp-content/uploads/2018/03/Guard-output-768x339.jpg 768w, /wp-content/uploads/2018/03/Guard-output-400x177.jpg 400w, /wp-content/uploads/2018/03/Guard-output.jpg 634w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></p>
<p>Let&#8217;s do some more coding on the nav.component.html and nav.component.ts for making our app more meaningful.</p>
<p><strong>nav.component.ts</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {

  constructor(private auth: AuthService) { }

  ngOnInit() {
  }

}
</pre>
<p><strong>nav.component.html</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">&lt;mat-toolbar color="primary"&gt;
  &lt;button mat-button routerLink="/home"&gt;Home&lt;/button&gt;
  &lt;button mat-button *ngIf="!auth.isLoggednIn()" routerLink="/register"&gt;Register&lt;/button&gt;
  &lt;button mat-button *ngIf="!auth.isLoggednIn()" routerLink="/login"&gt;Login&lt;/button&gt;
  &lt;button mat-button *ngIf="auth.isLoggednIn()" (click)="auth.logout()"&gt;Logout&lt;/button&gt;
&lt;/mat-toolbar&gt;</pre>
<p>Here we are just making the log out button available only for logged in users and hiding register and login button for logged in user. Sounds good? The auth.isLoggedIn function will be available on this page as we are injecting the auth service on out nav.component.ts file.</p>
<h2><span id="conclusion">Conclusion</span></h2>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/implementing-guard-in-angular-5-app/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Implement Validations in Angular 5 App</title>
		<link>https://mail.sibeeshpassion.com/implement-validations-in-angular-5-app/</link>
					<comments>https://mail.sibeeshpassion.com/implement-validations-in-angular-5-app/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 02 Dec 2017 19:50:08 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Validations]]></category>
		<category><![CDATA[Angular Validations]]></category>
		<category><![CDATA[Simple Angular Validation]]></category>
		<category><![CDATA[Two way binding in Angular]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12559</guid>

					<description><![CDATA[[toc] Introduction This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In this post, we are going to implement Two Way binding and validations in  Angular 5 registration form. So at the end of this article, you will be proficient in how to do validations in Angular. I hope you will like this article. Developing an Angular 5 App series These are the previous posts in this series. Please [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In this post, we are going to implement Two Way binding and validations in  <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5 registration form. So at the end of this article, you will be proficient in how to do validations in Angular. I hope you will like this article.</p>
<h3><em>Developing an Angular 5 App</em> series</h3>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
<li><a href="http://sibeeshpassion.com/implement-validations-in-angular-5-app/">Implement Validations in Angular 5 App</a></li>
</ol>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h3>Background</h3>
<p>Validations are having a vital role in all the applications, without validation, anyone can push invalid data to your application. So here we are also going to implement some validations, it is our application and we want to make it perfect right?</p>
<h3>Validation in Angular</h3>
<p>To get started with the Angular forms, we need to import some modules to our app.module.ts</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { FormsModule, ReactiveFormsModule } from '@angular/forms'</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">@NgModule({
  declarations: [
    AppComponent,
    RegistrationComponent,
    HomeComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    FormsModule, ReactiveFormsModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [],
  bootstrap: [AppComponent]
})</pre>
<p>In our previous post, we have developed an Angular form in the component named Registration. Now let us open <em>registration.component.ts </em>file and import FormBuilder, Validators in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">import { FormBuilder, Validators } from '@angular/forms';</pre>
<p>Let&#8217;s inject the FormBuilder in our constructor.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">constructor(private fb: FormBuilder) {}</pre>
<p>Next, is building a form group, so that we can include our model in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">form;
  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.required],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    });
  }</pre>
<p>In the group model, the first argument is the initial value that you may need to show. You can always do as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">firstName: ['Sibeesh', Validators.required]</pre>
<p>We will have to do some more changes in our registration.component.html.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-card&gt;
 &lt;form [formGroup]="form"&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput placeholder="First Name" formControlName="firstName" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput placeholder="Last Name" formControlName="lastName" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput type="email" placeholder="Email" formControlName="email" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput type="password" placeholder="Password" formControlName="password" /&gt;
 &lt;/mat-input-container&gt;
 &lt;mat-input-container&gt;
 &lt;input matInput type="password" placeholder="Confirm Password" formControlName="confirmPassword" /&gt;
 &lt;/mat-input-container&gt;
 &lt;button mat-raised-button color="primary"&gt;Register&lt;/button&gt;
 &lt;/form&gt;
&lt;/mat-card&gt;
</pre>
<p>Here <em>formControlName </em>is the tag which connects our model value and the control, so if you are not providing this value in your HTML, the validation for that particular control will not work. Now let us run our application and see the output.</p>
<div id="attachment_12561" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_Form_With_Validation-e1510909875736.png"><img decoding="async" aria-describedby="caption-attachment-12561" class="size-full wp-image-12561" src="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_Form_With_Validation-e1510909875736.png" alt="Angular_Form_With_Validation" width="634" height="309" /></a><p id="caption-attachment-12561" class="wp-caption-text">Angular_Form_With_Validation</p></div>
<p>Please be noted that we have given value only for the field First Name, so the remaining fields are showing in red color when we click our Register button. So our validation is working as expected.</p>
<p>You can always apply some custom validations too, like Email field validators. Let&#8217;s do that now.  Please change your constructor as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">constructor(private fb: FormBuilder, private auth: AuthService) {
    this.form = fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', [Validators.required, isEmailValid('email')]],
      password: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    });
  }</pre>
<p>Now as you guessed, we need to implement the function <strong>isEmailValid</strong>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function isEmailValid(control) {
  return control =&gt; {
    var regex = /^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return regex.test(control.value) ? null : { invalidEmail: true };
  }
}</pre>
<p>Now that we have done our custom validation, let&#8217;s check it out in our application.</p>
<div id="attachment_12584" style="width: 624px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App.png"><img decoding="async" aria-describedby="caption-attachment-12584" class="size-full wp-image-12584" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App.png" alt="Custom Email Field Validator in Angular 5 App" width="614" height="537" srcset="/wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App.png 408w, /wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App-300x262.png 300w, /wp-content/uploads/2017/12/Custom-Email-Field-Validator-in-Angular-5-App-400x350.png 400w" sizes="(max-width: 614px) 100vw, 614px" /></a><p id="caption-attachment-12584" class="wp-caption-text">Custom Email Field Validator in Angular 5 App</p></div>
<p>Let&#8217;s create a click event to our register button and get the form values that we have typed, so that we can pass these values to our server and save the same in our next article.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;button mat-raised-button (click)="register()" color="primary"&gt;Register&lt;/button&gt;</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js"> register() {
    console.log(this.form.value);
}</pre>
<p>Please make sure that you are getting the values in your browser console.</p>
<div id="attachment_12585" style="width: 362px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Get-the-form-values-e1512243815962.png"><img decoding="async" aria-describedby="caption-attachment-12585" class="size-full wp-image-12585" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Get-the-form-values-e1512243815962.png" alt="Get the form values" width="352" height="357" /></a><p id="caption-attachment-12585" class="wp-caption-text">Get the form values</p></div>
<p><em> </em></p>
<p>That&#8217;s all for today. In our next article, we can do some database actions, be ready.</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/implement-validations-in-angular-5-app/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generating Your First Components And Modules in Angular 5 App</title>
		<link>https://mail.sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/</link>
					<comments>https://mail.sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 16 Nov 2017 16:12:09 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular Components]]></category>
		<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[Angular Modules]]></category>
		<category><![CDATA[Creating Registration Form in Angular App]]></category>
		<category><![CDATA[Routing in Angular 5]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12548</guid>

					<description><![CDATA[[toc] Introduction This post is a continuation of the course Developing an Angular 5 App series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In our previous posts, we saw about the Angular 5 updates, an overview of the project and how to set up your first application in Angular 5. In this post, we are going to create few components and modules like routing, navigation, registration forms etc. So at the end of this article, you will be having a registration application [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>This post is a continuation of the course <em>Developing an Angular 5 App</em> series if you haven&#8217;t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. In our previous posts, we saw about the <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5 updates, an overview of the project and how to set up your first application in Angular 5. In this post, we are going to create few components and modules like routing, navigation, registration forms etc. So at the end of this article, you will be having a registration application with navigation and routing enables. I hope you will like this article.</p>
<h3><em>Developing an Angular 5 App</em> series</h3>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
</ol>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h3>Background</h3>
<p>So as I mentioned, here we are going to create an Angular 5 application which contains Registration form, Navigation, Routing etc.</p>
<h3>Let&#8217;s Develop Our Application</h3>
<p>We will be creating our application in a step by step manner so that you can easily follow up. No more talking now and let&#8217;s code it.</p>
<h4>Creating your first component</h4>
<p>As we discussed in our previous posts, a component is a set of combined functionality, in our case, we are going to create a component called Registration whose purpose is to serve all the codes for Registration.</p>
<p>You can create your components in two ways,</p>
<ol>
<li>Manually create a file called <em>registration.component.ts, </em>if you opt this method, you will have to register this component in <em>app.module.ts </em>yourself and also creating the template.</li>
<li>Using a command in NPM command prompt, this is an easy method, as it does all the background work for us.</li>
</ol>
<p>I am going to opt the second method. To create a component using your command prompt, you will have to run the following command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">ng generate component {component name }
</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5\ng5&gt;ng g component registration</pre>
<p>Once you run the command, the following processes will be happened.</p>
<ol>
<li>create src/app/registration/registration.component.html</li>
<li>create src/app/registration/registration.component.spec.ts</li>
<li>create src/app/registration/registration.component.ts</li>
<li>create src/app/registration/registration.component.scss</li>
<li>update src/app/app.module.ts (501 bytes)</li>
</ol>
<p>Now let us go back to our code folder and see the files. You can see your new files in app/registration folder. Here is how our registration.component.ts file looks like.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.scss']
})
export class RegistrationComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}
</pre>
<p>If you see the code, the command had created all of the code which we need to get started. The same component will be imported and added to our declarations in @NgModule in our <em>app.module.ts. </em>Please go ahead and see the same.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { RegistrationComponent } from './registration/registration.component';


@NgModule({
  declarations: [
    AppComponent,
    RegistrationComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<h4>Creating a registration form</h4>
<p>Now that we have created our component, let&#8217;s edit our component with needed text boxes and button. Go to your <em>registration.component.html </em>file and edit the content as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;p&gt;
  &lt;input type="text" placeholder="First Name" /&gt;
  &lt;input type="text" placeholder="Last Name" /&gt;
  &lt;input type="email" placeholder="Email" /&gt;
  &lt;input type="password" placeholder="Password" /&gt;
  &lt;input type="password" placeholder="Confirm Passwrod" /&gt;
  &lt;br/&gt;
  &lt;button&gt;Register&lt;/button&gt;
&lt;/p&gt;
</pre>
<h4>Creating a route for our new component</h4>
<p>Now our registration page is updated, and we are yet to create a route for the same right, let&#8217;s create it now and test our registration page.</p>
<p>To create a route you will have to do some set of changes.</p>
<h5>Make sure that you have one base element in your src/index.html file</h5>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;base href="/"&gt;</pre>
<h5>Now go to your app.module.ts file and import the RouterModule there</h5>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { RouterModule, Routes } from '@angular/router';</pre>
<h5>Create our Route Array</h5>
<pre class="EnlighterJSRAW" data-enlighter-language="js">const myRoots: Routes = [
  { path: 'register', component: RegistrationComponent }
];</pre>
<p>Here the path is the route name and component is the component which that path refers to.</p>
<h5>Configure the route in imports</h5>
<p>Once we create the routing array, it is time to configure it, using RouterModule.forRoot.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">@NgModule({
  declarations: [
    AppComponent,
    RegistrationComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [],
  bootstrap: [AppComponent]
})</pre>
<h5>Set our router outlet</h5>
<p>We have successfully configured our route, now we need to set where this pages/components to appear. To do so, go to your <em>app.component.html </em>and add the router-outlet. So the content of the route components will be displayed after the router-outlet tag.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;!--The content below is only a placeholder and can be replaced.--&gt;
&lt;div style="text-align:center"&gt;
  &lt;h1&gt;
    Welcome to {{title}}!
  &lt;/h1&gt;
  
&lt;/div&gt;
&lt;router-outlet&gt;&lt;/router-outlet&gt;
</pre>
<p>Now if you run our application by following the route as <em>http://localhost:4200/register</em> you can see our registration page as preceding.</p>
<div id="attachment_12549" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/11/Sample_Registration_Form-e1510816878711.png"><img decoding="async" aria-describedby="caption-attachment-12549" class="wp-image-12549 size-full" src="http://sibeeshpassion.com/wp-content/uploads/2017/11/Sample_Registration_Form-e1510816878711.png" alt="Sample_Registration_Form" width="634" height="104" /></a><p id="caption-attachment-12549" class="wp-caption-text">Sample_Registration_Form</p></div>
<p>Isn&#8217;t this registration form too basic, let&#8217;s style them now?</p>
<h4>Style registration page using material design</h4>
<p>Before we do anything, we need to install angular-material to our project. So that we can use the styles which are available there.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save @angular/material @angular/cdk</pre>
<p>By any chance, if you get an error as below,</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5\ng5&gt;npm install --save @angular/material @angular/cdk
npm ERR! path D:\SVenu\FullStackDevelopment\Angular\Angular5\ng5\node_modules\fsevents\node_modules\dashdash\node_modules
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall scandir
npm ERR! Error: EPERM: operation not permitted, scandir 'D:\SVenu\FullStackDevelopment\Angular\Angular5\ng5\node_modules\fsevents\node_modules\dashdash\node_modules'
npm ERR! { Error: EPERM: operation not permitted, scandir 'D:\SVenu\FullStackDevelopment\Angular\Angular5\ng5\node_modules\fsevents\node_modules\dashdash\node_modules'
npm ERR! stack: 'Error: EPERM: operation not permitted, scandir \'D:\\SVenu\\FullStackDevelopment\\Angular\\Angular5\\ng5\\node_modules\\fsevents\\node_modules\\dashdash\\node_modules\'',
npm ERR! errno: -4048,
npm ERR! code: 'EPERM',
npm ERR! syscall: 'scandir',
npm ERR! path: 'D:\\SVenu\\FullStackDevelopment\\Angular\\Angular5\\ng5\\node_modules\\fsevents\\node_modules\\dashdash\\node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
</pre>
<p>You should try running the following command before you execute the above command again.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">cmd.exe npm</pre>
<p>You may also need to install the animation as well</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save @angular/animations</pre>
<p>Once you have installed it, we need to import the some of the modules in the app.module.ts file as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule } from '@angular/material';</pre>
<p>Now add those components to our import list in @NgModule.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">@NgModule({
  declarations: [
    AppComponent,
    RegistrationComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [],
  bootstrap: [AppComponent]
})</pre>
<p>Let&#8217;s go back to our registration.component.html file and do some design changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-card&gt;
  &lt;mat-input-container&gt;
    &lt;input matInput type="text" placeholder="First Name" /&gt;
  &lt;/mat-input-container&gt;
  &lt;mat-input-container&gt;
    &lt;input matInput type="text" placeholder="Last Name" /&gt;
  &lt;/mat-input-container&gt;
  &lt;mat-input-container&gt;
    &lt;input matInput type="email" placeholder="Email" /&gt;
  &lt;/mat-input-container&gt;
  &lt;mat-input-container&gt;
    &lt;input matInput type="password" placeholder="Password" /&gt;
  &lt;/mat-input-container&gt;
  &lt;mat-input-container&gt;
    &lt;input matInput type="password" placeholder="Confirm Passwrod" /&gt;
  &lt;/mat-input-container&gt;
  &lt;br /&gt;
  &lt;button mat-raised-button color="primary"&gt;Register&lt;/button&gt;
&lt;/mat-card&gt;
</pre>
<p>We also need to include one material CSS in our Style.scss file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="css">@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';</pre>
<p>Now let&#8217;s run our application and see our registration page.</p>
<div id="attachment_12552" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/11/Material_Angular_Form-e1510836044744.png"><img decoding="async" aria-describedby="caption-attachment-12552" class="wp-image-12552 size-full" src="http://sibeeshpassion.com/wp-content/uploads/2017/11/Material_Angular_Form-e1510836044744.png" alt="Material_Angular_Form" width="634" height="281" /></a><p id="caption-attachment-12552" class="wp-caption-text">Material_Angular_Form</p></div>
<p>That&#8217;s cool, we have done it.</p>
<h4>Create Home and Navigation Components</h4>
<p>We know how to create new components now using generate command right, let&#8217;s create a new component for Home and Navigation.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">ng g component home 

ng g component nav</pre>
<p>As we used the commands to create the components, the same will be imported in our app.module.ts automatically, so we don&#8217;t need to worry about it.</p>
<p>Now let&#8217;s edit our nav component and use a material design for the navigation buttons.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;mat-toolbar color="primary"&gt;
  &lt;button mat-button routerLink="/"&gt;Home&lt;/button&gt;
  &lt;button mat-button routerLink="/register"&gt;Register&lt;/button&gt;
&lt;/mat-toolbar&gt;
</pre>
<p>Here routerLink property specifies the route where we need to redirect to. We are not done yet, we need to use this component on our app.component.html page to see this navigation.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;!--The content below is only a placeholder and can be replaced.--&gt;
&lt;div style="text-align:center"&gt;
  &lt;h1&gt;
    Welcome to {{title}}!
  &lt;/h1&gt;
  &lt;app-nav&gt;&lt;/app-nav&gt;
&lt;/div&gt;
&lt;router-outlet&gt;&lt;/router-outlet&gt;
</pre>
<p>And also add our new route for our HomeComponent. So go to your app.module.ts and edit your route as follows.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">const myRoots: Routes = [
  { path: '', component: HomeComponent },
  { path: 'register', component: RegistrationComponent }
];</pre>
<p>Let&#8217;s give it a try now, I am sure that you will be seeing an output as preceding.</p>
<div id="attachment_12553" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/11/Nav_Demo-e1510838066336.png"><img decoding="async" aria-describedby="caption-attachment-12553" class="wp-image-12553 size-full" src="http://sibeeshpassion.com/wp-content/uploads/2017/11/Nav_Demo-e1510838066336.png" alt="Nav_Demo" width="634" height="250" /></a><p id="caption-attachment-12553" class="wp-caption-text">Nav_Demo</p></div>
<p>That&#8217;s all for today. In our next article, we will start to do some validations and set up two-way data binding, so that the model values can be passed to the server. Till then bye.</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Angular 5 Basic Demo Project Overview</title>
		<link>https://mail.sibeeshpassion.com/angular-5-basic-demo-project-overview/</link>
					<comments>https://mail.sibeeshpassion.com/angular-5-basic-demo-project-overview/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 15 Nov 2017 18:07:04 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 App Overview]]></category>
		<category><![CDATA[Project Overview Angular 5]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12541</guid>

					<description><![CDATA[[toc] Introduction This post is a continuation of the Angular 5 series and you can find the first part of this series here What Is New and How to Set Up our First Angular 5 Application. So if you haven&#8217;t gone through the first part yet, I strongly recommend you to do that. In our first part, we saw the Angular 5 updates and how to set up your first application in Angular 5. In this post we are going to discuss few files and application overview, we will also be discussing some key points like Components, Declarations, Modules, Providers etc. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>This post is a continuation of the Angular 5 series and you can find the first part of this series here <a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a>. So if you haven&#8217;t gone through the first part yet, I strongly recommend you to do that. In our first part, we saw the <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5 updates and how to set up your first application in Angular 5. In this post we are going to discuss few files and application overview, we will also be discussing some key points like Components, Declarations, Modules, Providers etc. So at the end of this article, you will have some basic understanding of Angular project structures and what it really matter when it comes to the project. I hope you will like this article.</p>
<h3><span id="developing-an-angular-5-app-series"><em>Developing an Angular 5 App</em> series</span></h3>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
</ol>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h3>Background</h3>
<p>Though Angular 5 has exactly same project architecture as the previous version, we will be explaining some key elements so that the beginners can follow up this series. I hope you would not mind if you are an experienced professional. Thanks for understanding.</p>
<h3>Understanding Angular Application</h3>
<p>The Angular project has a clean architecture, it contains the folder structure as shown in the preceding image.</p>
<div id="attachment_12542" style="width: 483px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_App_Folder_Structure.png"><img decoding="async" aria-describedby="caption-attachment-12542" class="size-full wp-image-12542" src="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_App_Folder_Structure.png" alt="Angular_App_Folder_Structure" width="473" height="510" srcset="/wp-content/uploads/2017/11/Angular_App_Folder_Structure.png 473w, /wp-content/uploads/2017/11/Angular_App_Folder_Structure-278x300.png 278w, /wp-content/uploads/2017/11/Angular_App_Folder_Structure-400x431.png 400w" sizes="(max-width: 473px) 100vw, 473px" /></a><p id="caption-attachment-12542" class="wp-caption-text">Angular_App_Folder_Structure</p></div>
<p>We are going to start developing our application in src/app folder which is our application root folder. For now, let&#8217;s go ahead and see what we have got in the existing files. Let us open the file <em>app.component.ts.</em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
}
</pre>
<p>In Angular we are creating components for each selected functionalities, let&#8217;s say one component for login, and other for the register, other for navigation etc, so that each can be maintained separately. In each component, we have 3 parts.</p>
<ol>
<li>Import section</li>
<li>Decoration</li>
<li>Export section</li>
</ol>
<p>Import section helps us to import some existing functionalities available in the framework like we have included Component from Angular/core in the above code snippet.</p>
<p>The Decoration is the place where we decorate the component, giving a selector( which is unique to each component), Style the UI, Giving the template URL which points to a particular HTML file where we customize the component. We can also include our template in our decoration itself as a template:&#8217;here your custom HTML&#8217;.</p>
<p>The Export section includes the custom TypeScript code which is specific to that component. Let&#8217;s say it is a class, which holds its own functionalities.</p>
<p>Now let us just move our pointer to <em>app.module.ts, </em>this is the place where we register all of our modules, components, providers etc. We can consider this as a base class. Like components, it has a section for imports and export. It also has a @NgModule section, which contains our declarations (components), imports (modules), providers (services).</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</pre>
<p>I am not going to explain about app.component.css, app.component.html, app.component.spec.ts as you can see what it has, by seeing the code inside. So I am leaving that to you.</p>
<p>If you see the project folder, you can see a folder named <em>Environment, </em>as the name implies, it helps us to set the configurations for our environments, let&#8217;s say for development and production etc.</p>
<p><em>Index.html </em> is the main page from which we call the <em>app-root, </em>remember we set the app.component&#8217;s selector as <em>app-root</em>?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
  &lt;meta charset="utf-8"&gt;
  &lt;title&gt;MyAngular5App&lt;/title&gt;
  &lt;base href="/"&gt;

  &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
  &lt;link rel="icon" type="image/x-icon" href="favicon.ico"&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;app-root&gt;&lt;/app-root&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<blockquote><p>Please make sure that you are giving &lt;base href=&#8221;/&#8221;&gt; in your index.html file, orelse you will get an error in your agular app.</p></blockquote>
<p><em>The tsconfig.app.json </em>file is the place where we can set the configuration for our project, like setting the module versions, compiler options etc. You can see a sample file as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
</pre>
<p>If you have created your Angular app using Angular CLI, you will see a file named <em>.angular-</em>cli<em>.</em>json<em> </em>in your project. This is the file where all of your custom project settings rreside.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "my-angular5-app"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}
</pre>
<p>Last but not the least <em>package.json </em>is the file where your NPM packages are mentioned, and whenever you run <em>npm install </em>commands, this is the file that command look into.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "name": "my-angular5-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.5.0",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.4.2"
  }
}
</pre>
<p>Once the package manager finishes running the install command, all the mentioned packages will be added to the folder <strong>node_modules.</strong></p>
<p>In our next article, we will start developing some components in our Angular app. Till then bye.</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/angular-5-basic-demo-project-overview/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>What Is New and How to Set Up our First Angular 5 Application</title>
		<link>https://mail.sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/</link>
					<comments>https://mail.sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 15 Nov 2017 11:05:26 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Angular 5]]></category>
		<category><![CDATA[Angular 5 Basic App]]></category>
		<category><![CDATA[First Angular 5 App]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12535</guid>

					<description><![CDATA[[toc] Introduction We all know that the Angular version 5 is released a few weeks back, aren&#8217;t you eager to know what is there we have got in Angular 5. What makes our development easy there? Well, here in this post I am going to discuss few updates in Angular 5. By saying that,  I will not be discussing all the items which have been released with this version. Here, we will also be checking how to create our first Angular 5 application. So at the end of this article, you will have your own sample application with you. Cheers [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>We all know that the Angular version 5 is released a few weeks back, aren&#8217;t you eager to know what is there we have got in <a href="http://sibeeshpassion.com/category/client-side-technologies/angular/">Angular</a> 5. What makes our development easy there? Well, here in this post I am going to discuss few updates in Angular 5. By saying that,  I will not be discussing all the items which have been released with this version. Here, we will also be checking how to create our first Angular 5 application. So at the end of this article, you will have your own sample application with you. Cheers for that. I hope you will like this article.</p>
<h3><span id="developing-an-angular-5-app-series"><em>Developing an Angular 5 App</em> series</span></h3>
<p>These are the previous posts in this series. Please go ahead and have a look.</p>
<ol>
<li><a href="http://sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/">What Is New and How to Set Up our First Angular 5 Application</a></li>
<li><a href="http://sibeeshpassion.com/angular-5-basic-demo-project-overview/">Angular 5 Basic Demo Project Overview</a></li>
<li><a href="http://sibeeshpassion.com/generating-your-first-components-and-modules-in-angular-5-app/">Generating Your First Components And Modules in Angular 5 App</a></li>
</ol>
<h3>Source Code</h3>
<p>You can always clone or download the source code <a href="https://github.com/SibeeshVenu/ng5">here</a></p>
<h3>Background</h3>
<p>As I mentioned earlier, this post is going to give you an introduction to the changes or updates in Angular 5. The application we are going to create is a basic Angular application with the help Angular CLI and NPM (Node Package Manager). So if you have not installed <a href="http://sibeeshpassion.com/category/client-side-technologies/node-js/">NodeJS</a> on your machine, please go ahead and install it from <a href="https://nodejs.org/en/">here</a>. Now let&#8217;s see the key updates in Angular 5.</p>
<h3>What is new in Angular 5?</h3>
<p>Though there are quite a few updates, I would say more concentration was given to the area of performance and efficiency. Below is the list of key area updates.</p>
<h4>AOT compiler</h4>
<p>AOT is Ahead of Time compiler, what it does is, as the name implies, it converts all of our TypeScript codes to native JavaScript code to make sure that it supports in all the browsers. The same was being done by Just In Compiler in the previous version, so what makes the difference? AOT converts the code before it runs in the browser, whereas JIT converts it at runtime.  Hence the page renders faster.</p>
<h4>Optimizations</h4>
<p>As I mentioned earlier, the development team was concentrating more on the performance aspects of Angular 5. Two of such improvements are,</p>
<ol>
<li>Boost speed</li>
<li>Smaller Bundles</li>
</ol>
<h4>Package Updates</h4>
<p>There are some updates in few packages, and some of them are,</p>
<ol>
<li>Now Angular CLI 1.5 has Angular 5</li>
<li>RXJS version is been upgraded to 5.5</li>
<li>TypeScript is been updated to 2.4</li>
</ol>
<h4>New HttpClient</h4>
<p>There are some changes in some modules as well, the new HttpClient module is faster and lighter than the previous version. Hence the old Http module is deprecated, however, you can still use the same in your applications, it is just that, the same will vanish in any future updates. The new module can be imported as below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">Import {HttpClientModule} from ‘@angular/common/http’</pre>
<h4>Other Updates</h4>
<p>There are some other updates related to many modules and categories. Few of them are,</p>
<ol>
<li>Some changes in form validation, specifically in blur and on submit</li>
<li>The pipes are more standardized and internationalized now</li>
<li>Old pipes are deprecated now</li>
<li>A new module ServerTransferStateModule is introduced</li>
</ol>
<p>Sorry that I am not including any code snippets to highlight the actual changes, I will be writing an article very soon with full code changes.</p>
<h3>Creating your first Angular 5 application</h3>
<p>To create an Angular application easily, the first thing you may need to do is, Installing Angular CLI. I hope you had already done it. Let&#8217;s just jump into the process now.</p>
<p>Open your Node Package Manager Console and create a directory where we are going to download all the Angular files.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">mkdir Angular5</pre>
<p>Now we can move our cursor to that folder.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">cd Angular5</pre>
<p>Now we can check whether the Node and NPM is already installed or not.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">D:\SVenu\FullStackDevelopment\Angular\Angular5&gt;node -v</pre>
<p>If it is installed you will get the version, for me it was v7.9.0</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5&gt;npm -v</pre>
<p>My NPM version is 4.2.0</p>
<p>By any chance, if you need to update your NPM version, you can always do that with the help of the preceding command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5&gt;npm i -g npm</pre>
<p>Once after I update my NPM version, the command <em>npm -v </em>was showing as 5.5.1. So now we are good to go. Our next step is to install Angular CLI, let&#8217;s do it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5&gt;npm install @angular/cli -g</pre>
<p>If you want to check the version of your Angular CLI, you can use the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5&gt;ng -v</pre>
<p>The result may look like below.</p>
<blockquote><p>Angular CLI: 1.5.0<br />
Node: 7.9.0<br />
OS: win32 ia32<br />
Angular:<br />
&#8230;</p></blockquote>
<p>Now it is time to create our Angular Project, please use the preceding command for the same.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5&gt;ng new MyAngular5App</pre>
<p>Here MyAngular5App is the project name. Once you run the command, it will do 3 tasks.</p>
<ol>
<li>Creating the components which are needed</li>
<li>Installing packages for tooling via npm.</li>
<li>Initializing git</li>
</ol>
<p>Now if you go to your project directory, you can see all the files has been included there already. You can go ahead and open the files in any source code editors.</p>
<p>As the last step, we need to run our application.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">D:\SVenu\FullStackDevelopment\Angular\Angular5&gt;cd MyAngular5App

D:\SVenu\FullStackDevelopment\Angular\Angular5\MyAngular5App&gt;ng serve</pre>
<p>The above command will build your application and serve the port 4200 by default. You may see the preceding output in the command window.</p>
<blockquote><p>** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **<br />
Date: 2017-11-15T07:45:17.925Z<br />
Hash: dd334581365d3dd74dfd<br />
Time: 21845ms<br />
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]<br />
chunk {main} main.bundle.js (main) 24.3 kB [initial] [rendered]<br />
chunk {polyfills} polyfills.bundle.js (polyfills) 554 kB [initial] [rendered]<br />
chunk {styles} styles.bundle.js (styles) 34.9 kB [initial] [rendered]<br />
chunk {vendor} vendor.bundle.js (vendor) 8.03 MB [initial] [rendered]</p>
<p>webpack: Compiled successfully.</p></blockquote>
<p>Let&#8217;s run our application by running  <a href="http://localhost:4200">http://localhost:4200</a> now. I am sure you will get an Angular application as preceding.</p>
<div id="attachment_12538" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_5-e1510740234143.png"><img decoding="async" aria-describedby="caption-attachment-12538" class="size-full wp-image-12538" src="http://sibeeshpassion.com/wp-content/uploads/2017/11/Angular_5-e1510740234143.png" alt="Angular_5" width="634" height="375" /></a><p id="caption-attachment-12538" class="wp-caption-text">Angular_5</p></div>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/what-is-new-and-how-to-set-up-our-first-angular-5-application/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
	</channel>
</rss>
