Monday, July 23, 2018

Custom Directives in angular 2, 4, 5, 6

   Custom Directives 


- Creating our own directive based on application requirement
  Called as Custom Directive.

- In Angular, we can Use Custom Directives in 2 ways.

1) Attribute Type

2) Structural Type


 Attribute Type 


- Directive is the predefined class used to create the Custom Directive

- ElementRef is the Predefined Class used to manipulate the DOM Elements.

- HostListener is the Predefined Class used to apply the mouse events.

- Input is the Predefined Class used to pass the Dynamic Data to Custom Directive.

- Attribute Type Custom Directive won't work with the DOM Directly(memory).



         Structural Type Custom Directives 

- Structural Type Custom Directives will works with the DOM Directly.

- Structural Type Custom Directives prefix with "*"

- TemplateRef is the predefined class used to manipulate the Templates

- ViewContainerRef used to manipulate the DOM.


myDirective.ts 


import { Directive,
  ElementRef,
  HostListener,
  Input } from "@angular/core";
@Directive({
selector:"[myDir]"
})        
export class MyDirective{
@Input() var_one;
@Input() var_two;
constructor(private _el:ElementRef){}
public hiliteColor(color){
 this._el.nativeElement.style.backgroundColor = color;
}
@HostListener("mouseenter") onmouseenter(){
 this.hiliteColor(this.var_one);
};
@HostListener("mouseleave") onmouseleave(){
 this.hiliteColor(this.var_two);
};
}



app.component.ts 

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}




app.component.html 

<h1 [var_one]=color_one [var_two]=color_two myDir>Hello....!</h1>

<input type="color" [(ngModel)]="color_one"> <br><br>
<input type="color" [(ngModel)]="color_two"> <br><br>


<h1 *hello=false>Hi....!</h1>


structural.directive.ts 

import { Directive,
  TemplateRef,
  Input,
  ViewContainerRef } from "@angular/core";
@Directive({
selector:"[hello]"
}) 
export class StructuralDirective{
constructor(private _templateRef:TemplateRef<any>,
         private _viewContainerRef:ViewContainerRef){}
@Input() set hello(isHidden:boolean){
 if(isHidden){
     this._viewContainerRef.createEmbeddedView(this._templateRef);
 }else{
     this._viewContainerRef.clear();
 }
}           
}      



app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyDirective } from "./my.directive";
import { FormsModule } from "@angular/forms";
import { StructuralDirective } from "./structural.directive";
@NgModule({
  declarations: [
    AppComponent,
    MyDirective,
    StructuralDirective
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }




Saturday, July 21, 2018

Model Driven Forms

Model Driven Forms 


- Model Driven Forms also called as Reactive Forms.

- Model Driven Forms mainly on Model.

- [formGroup] is the predefined directive used to assign the logical name to form.

- formControlName is the predefined directive used to declare the form elements.

- formGroupName is the predefined directive used to create the "sub groups".

- Reactive forms available on "ReactiveFormsModule"

- "ReactiveFormsModule" available in "@angular/forms" package.


******************************************
MDFEx
src
    app
app.component.ts
app.conponent.html


app.module.ts
index.html
******************************************

app.component.ts

import { Component } from '@angular/core';
import { FormGroup,FormControl, Validators } from "@angular/forms";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private myForm:FormGroup;

  ngOnInit(){
    this.myForm = new FormGroup({
        fname:new FormControl("Naresh",[Validators.required,
                                        Validators.minLength(3),
                                        Validators.maxLength(6)]),
        lname:new FormControl(),
        uemail:new FormControl(),
        addr:new FormGroup({
          ucity:new FormControl(),
          uaddress:new FormControl()
        }),
        gender:new FormControl(),
        ucountry:new FormControl()
    });
  }

  public clickMe():any{
      console.log(this.myForm.value);
  }
}




app.component.html


<div class="container">
  <form [formGroup]="myForm" (ngSubmit)="clickMe()">
     
      <!--First Name-->
      <div class="form-group">
        <label>First Name.</label>
        <input type="text"
               class="form-control"
               formControlName="fname"
               required>
      </div>
      <div class="alert alert-danger"
          *ngIf="myForm.controls['fname'].hasError('required')">
          *** Can't Left Blank *** 
      </div>
      <div class="alert alert-warning"
           *ngIf="myForm.controls['fname'].hasError('minlength')">
            *** Minimum 3 characters are required ***
      </div>
      <div class= "alert alert-success"
           *ngIf="myForm.controls['fname'].hasError('maxlength')">
          *** maximum 6 Chatacters Are Allowed ***
      </div>

 
      <!--Last Name-->
      <div class="form-group">
          <label>Last Name.</label>
          <input type="text"
                 class="form-control"
                 formControlName="lname">
      </div>

      <!--Email-->
      <div class="form-group">
          <label>Email.</label>
          <input type="email"
                 class="form-control"
                 formControlName="uemail">
      </div>
 
      <!-- Sub Group-->
      <div class="form-group" formGroupName="addr">
          <!--City-->
          <div class="form-group">
            <label>City.</label>
            <input type="text"
                   class="form-control"
                   formControlName="ucity">
          </div>

           <!--Address-->
           <div class="form-group">
              <label>Address.</label>
              <input type="text"
                     class="form-control"
                     formControlName="uaddress">
           </div>
      </div>

      <!--Gender-->
      <div class="form-group">
          <input type="radio"
                 class="form-control"
                 value="male"
                 formControlName="gender">Male
          <input type="radio"
                 class="form-control"
                 value="female"
                 formControlName="gender">FeMale      
      </div>

      <!-- DropDown -->
      <div class="form-group">
          <select class="form-control" formControlName="ucountry">
            <option value="India">India</option>
            <option value="USA">USA</option>
            <option value="UK">UK</option>
            <option value="Canada">Canada</option>
          </select>
      </div>

      <!-- Submit Button -->
      <div align="center" style="margin-top: 20px">
          <input type="submit" class="btn btn-success">
      </div>
  </form>
</div>




app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { ReactiveFormsModule } from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }