Output with EventEmitter in Angular


Output and EventEmitter used together to pass data from Child component to Parent component. EventEmitter emits the data that can be received by parent component. In the below example We have two components appComponent(parent component) and childComponent(child components) child component contains textbox and parent component shows the data when user enters in the child component. Here we have used Two-way binding, we can also use ngModelChange event.

Example:



child-component.component.html

<div style="border:1px solid chocolate; width:300px; height: 120px; padding: 10px 10px">

   <b> Child component</b><br><br>
   Type here : <input type="text" [(ngModel)]='inputValue'  />
  </div>



child-component.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.css']
})
export class ChildComponentComponent{

private _inputValue:string;
get inputValue(){
  return this._inputValue;
}
set inputValue(value:string){
  this._inputValue=value;
  this.userName.emit(this._inputValue);
}

@Output() userName : EventEmitter<string>= new EventEmitter<string>();

}


app.component.html

<div style="border: 1px solid chocolate; height: 250px; width: 350px; padding: 10px 10px" >
 <span> <b>Parent component</b></span>
 <br><br>
 you entered {{messageFromChild}}
  <br><br>
  <child-component (userName)='OnDataChange($event)'></child-component>
</div>



app.component.ts

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

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

  public messageFromChild:string;

    OnDataChange(childData: string){
    this.messageFromChild=childData;
    }
}


Add FormsModule in the app.module.ts



That's It !!
Read More »

Detect changes in parent component using @Input and ngModelChange in Angular


Here we are going to see how the data will be communicated from parent component to child component using @Input() method.

@input() can be used in two ways.
·        Two way binding with @Input()
·        One way binding using ngOnChange() event and @input()

Here we gonna look at one way binding with ngModelChange with @Input().

Technical implementation:
            Here we have two component AppComponent (parent component) ChildComponent ( child component).

App component contains Textbox, When user enters any of the data, it will be passed to Child component and display as a span there.




app.component.ts


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 public inputValue : string;
  onChange(UpdatedValue : string) :void
  {
    this.inputValue = UpdatedValue;
  }
}


app.component.html

<div style="border: 1px solid chocolate; height: 250px;

width: 350px; padding: 10px 10px" > 
 <span> <b>Parent component</b></span>
 <br><br>
  Type here : <input type="text" [ngModel]='inputValue'
   (ngModelChange)='onChange($event)' />
  <br><br>
  <child-component [message]='inputValue'></child-component>
</div>



child-component.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.css']
})
export class ChildComponentComponent {
  @Input() message:string;
  constructor() { }
}


child-component.component.html

<div style="border:1px solid chocolate; width:300px;

   height: 120px; padding: 10px 10px">
   <b> Child component</b><br><br>
    you entered {{message}}
  </div>


Add FormsModule in the app.module.ts



That's It !!
Read More »

Sending data to child component using @Input and two-way binding in Angular

Here we are going to see how the data will be communicated from parent component to child component using @Input() method.

@input() can be used in two ways.
·        Two way binding with @Input()
·       ngOnChange() event and @input()

Here we gonna look at Two way binding with @Input().

Technical implementation:
            Here we have two component AppComponent (parent component) ChildComponent ( child component).
App component contains Textbox, When user enters any of the data, it will be passed to Child component and display as a span there.



app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public inputValue:string;
} 



app.component.html

<div style="border: 1px solid chocolate; height: 250px;
width: 350px; padding: 10px 10px" > 
 <span> <b>Parent component</b></span>
 <br><br>
  Type here : <input type="text" [(ngModel)]='inputValue' />
  <br><br>
  <child-component [message]='inputValue'></child-component>
</div>



child-component.component.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.css']
})
export class ChildComponentComponent {
  @Input() message:string;
  constructor() { }
}


child-component.component.html

<div style="border:1px solid chocolate; width:300px;
   height: 120px; padding: 10px 10px">
   <b> Child component</b><br><br>
    you entered {{message}}
  </div>


Add FormsModule in the app.module.ts



That's It !!
Read More »

Authentication for webapi

Earlier we have seen how to Create WEBAPI for GET POST PUT methods, as a part of security we can use userid & Password authentication for the service. Each time while the request has been received credentials in the headers are validated before giving response.

  1.   Create new Controller

Create get method to return some data from table.
Controller code with entity framework:

              using System.Threading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEBAPIAUTHORIZATION.Models;

namespace WEBAPIAUTHORIZATION.Controllers
{
    public class EmployeeController : ApiController
    {
        public HttpResponseMessage Get() //GET
        {
            string username = Thread.CurrentPrincipal.Identity.Name;
            using (ACT2_MINIQEntities entities = new ACT2_MINIQEntities())
            {
                var employeelist = entities.EmployeeDetails.ToList();
                return Request.CreateResponse(HttpStatusCode.OK, employeelist);
            }
        }
    }
}


2.   Create new class at the root folder of the webapi project.

In my case creating class with Security.cs


                  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WEBAPIAUTHORIZATION.Models;

namespace WEBAPIAUTHORIZATION
{
    public class Security
    {
        public static bool Login(string Username, string Password)
        {
            //Database connection to retrive daata
            using (ACT2_MINIQEntities entities = new ACT2_MINIQEntities())
            {
                //returns bool
                return entities.users.Any(
                        x => x.username.Equals(
                            Username, StringComparison.OrdinalIgnoreCase)
                            && x.passcode == Password);
            }
        }
    }
}


1.   Create Another new class at the root folder of webapi project.

In my case I have named as Authentication.cs


using System;
using System.Linq;
using System.Web.Http.Filters;
using System.Threading;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Security.Principal;
using System.Web.Http.Controllers;

namespace WEBAPIAUTHORIZATION
{
    public class Authentication : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                string authenToken = actionContext.Request.Headers.Authorization.Parameter;
                string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenToken));
                string[] credentials = decodedToken.Split(':');

                string userName = credentials[0];
                string password = credentials[1];

                if (Security.Login(userName, password))
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }
    }
}


4.       Changes in WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace WEBAPIAUTHORIZATION
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //to authenticate globally
            config.Filters.Add(new Authentication());
        }
    }
}


To test output, we should send the credentials in request headers

Credentials should be in format of   username:Password

Credentials should be encoded to base64 format. As shown below.

Read More »