<?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 Shared Directive &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/angular-shared-directive/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Mon, 23 Apr 2018 06:33:08 +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 Shared Directive &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 fetchpriority="high" 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>
	</channel>
</rss>
