Showing posts with label Typescript. Show all posts
Showing posts with label Typescript. Show all posts

Monday, 19 January 2026

How to create a custom component or control in React Typescript

 In this tutorial we are going to see how to create a custom control or component in React Typescript.

  1. Props and Ref as Input
  2. Html Template 
  3. Css

Why we need Props and Ref as Input, Props means input parameters that needs for component. Ref is used for Referring your component using Ref when it is accessed or used in the Html.


From the above you can see when RButton component is used we referred it as using UseRef. 

useImperativeHandle  used to expose the methods and properties to access a the parent component when it is referred at the time of usage, in this example we are exposing Id and click event for the ref. Now we can see the full implementation of RButton Component.

Full Component Implementation



Component CSS:


Now we can use it like Below

Output:





From this tutorial you can learn how to write the custom component in React Typescript





Saturday, 29 April 2017

create a component in angular 1.5 using Typescript

In this post we are going to see how to create the component in angular 1.5 using Typescript. first we have to understand what is component, component is a isolated directive with some functionalities, most of functionalities are look like same for directive and components, few things will change, we will see the how to write the components using Typescript

First we have to create the interface for bindings parameters, then implement that in a controller , later assign this controller to component, in component we have bindings parameters there also we have to specify the parameters.


export interface  StarBindings {
        ratingValue: any;
        max: number;
        readonly: boolean;
        starSize: number;
        onRatingChanged: (value: any) => any; }


In component

this.bindings = {
                ratingValue: '=',
                max: '=',
                readonly: '@',
                starSize: '=',
                onRatingChanged: '&'
            };



Then write logic inside the controller, later access everything using the $ctrl, which is automatically created alias by component.

module app.components {

    export interface  StarBindings {
        ratingValue: any;
        max: number;
        readonly: boolean;
        starSize: number;
        onRatingChanged: (value: any) => any;
    }

    class  StarController implements  StarBindings {

        public ratingValue: any;
        public max: number;
        public readonly: boolean;
        public starSize: number;
        public onRatingChanged: (value: any) => any;
        public stars: any =[];

        static  $inject = ['$log','$element','$scope'];

        constructor(private $log: ng.ILogService, private $element: ng.IAugmentedJQuery, 
                    private $scope: ng.IScope){

        }

        $postLink = (): void => {
            this.$log.info('post link invoked');
            this.drawStar();
        };

        drawStar = (): void => {
            this.$element.css('font-size',this.starSize+'px');
            this.$scope.ratingValue = 0;
            let t = this;
            this.$scope.$watch('ratingValue', function (oldval, newval) {
                if (newval) {
                    t.updateStars();
                }
            });

            this.$scope.ratingValue = this.ratingValue;

        };



        toggle =  (index: number) => {
            if (this.readonly && this.readonly === true) {
                return;
            }
            this.ratingValue = index + 1;
            this.$scope.ratingValue = this.ratingValue;
            this.onRatingChanged({ rating: index + 1 });

        };




        updateStars = (): void => {
            this.stars = [];
            for (let i:number = 0; i < this.max; i++) {
                this.stars.push({ filled: i < this.ratingValue });
            }
        }
    }

    class StarComponent {

        public bindings: any;
        public controller: any;
        public template: string;

        constructor(){
            this.template = '<ul class="rating">' +
                                '<li ng-repeat="star in $ctrl.stars" ng-class="star"'+
                                   ' ng-click="$ctrl.toggle($index)">' +
                                '\u2605' +
                                '</li>' +
                            '</ul>';
            this.controller = StarController;
            this.bindings = {
                ratingValue: '=',
                max: '=',
                readonly: '@',
                starSize: '=',
                onRatingChanged: '&'
            };
        }

    }

    angular.module('myapp').component('star',new StarComponent());
}

Here you can see that i am using the $postLink method to render the star , $postLink is a predefined method called by component, Assign the template, bindings, controller inside the component, star rendering logic are present inside the controller, i am using the $watch  here to render the star in the when user click.

app.controller.ts


/// <reference path="../node_modules/@types/angular/index.d.ts" />


module mymod{
    class MyController{

        private name: string;
        private sample: string;
        private title: string;
        private rating2: number;

        static $inject = ['$log']

        constructor(private $log: angular.ILogService){
            this.title = "Angular with Typescript";
            this.name = 'rajesh1';
            this.sample = 'raise';
            this.rating2 = 4;
        }

        save = (rating: any): void => {
            console.log('rating changed');
            console.log(rating);
        };


        dosomething = (): void => {
            window.setTimeout(3, () => { this.$log.warn('do something'); });
            
        }

    }
    var myApp= angular.module('myapp',[]);
    myApp.controller('mycontroller',MyController);
}



Html


<!DOCTYPE html>
<html lang="en" ng-app="myapp">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body ng-controller="mycontroller as vm">
      
        <h2 style="margin:20px">{{vm.title}}</h2>
        <br/>

        <star rating-value="vm.rating2" max="10" star-size="45"
              on-rating-changed="vm.save(rating)"></star>

        <link href="styles.css" rel="stylesheet" />
        <script src="bower_components/angular/angular.min.js"></script>
        <script src="app/app.js"></script>
        <script src="app/star.component.js"></script>

    </body>
</html>


CSS:


.rating {
    color: #a9a9a9;
    margin: 0;
    padding: 0;
}

ul.rating {
    display: inline-block;
}

.rating li {
    list-style-type: none;
    display: inline-block;
    padding: 1px;
    text-align: center;
    font-weight: bold;
    cursor: pointer;
}

.rating .filled {
    color: red;
}


Output:



From this post you can learn how to create components in angular 1.5 using Typescript




Friday, 14 April 2017

Create a angular 1.5 directive in Typescript

In this post we are going to see how to create a angular 1.5 directive in Typescript,  create the properties of return object as properties of diretive class, implements ng.IDirective in the directive class,

Then create a factory function which implements ng.IDirectiveFactory which returns the new instance of directive , where we inject the dependencies for Directive.

For example we are creating a star Directive which will render the star


module app.directives {

    export interface IStarController {
        getData(): void;
        updateStars(): void;
    }

    export interface IStarScope extends ng.IScope {
        toggle(index: number): void;
        readonly: string;
        ratingValue: number;
        onRatingChanged(input: Object): void;
        stars: any[];
        max: number;
        starSize: number;
    }

    class StarController implements IStarController {

        static $inject = ['$scope'];

        constructor(private $scope: IStarScope) {
                   
        }

        public getData() {
            console.log('scope'); 
            console.log(this.$scope);
        }

       
        updateStars = (): void => {
            this.$scope.stars = [];
            for (var i = 0; i < this.$scope.max; i++) {
                this.$scope.stars.push({ filled: i < this.$scope.ratingValue });
            }
        }


    }

    
    class StarDirective implements ng.IDirective {

        constructor(private logfactory: app.logfactory.ILOGFactory) {

        }

        public controller:any= StarController;
        public restrict: string = 'EA';
        public template: string = '<ul class="rating">' +
        '<li ng-repeat="star in stars" ng-class="star" ng-click="toggle($index)">' +
                                          '\u2605' +
                                    '</li>' +
                                  '</ul>';
        public scope: any = {
            ratingValue: '=',
            max: '=',
            readonly: '@',
            starSize: '=',
            onRatingChanged: '&'
        }
        public link: ng.IDirectiveLinkFn = (scope: app.directives.IStarScope, 
               elem: ng.IAugmentedJQuery, attr: ng.IAttributes, 
               ctrl: app.directives.IStarController) => {


            let logging = this.logfactory;

            elem.css('font-size', scope.starSize+'px');

            scope.toggle = function (index) {
                if (scope.readonly && scope.readonly === 'true') {
                    return;
                }
                scope.ratingValue = index + 1;

                scope.onRatingChanged({ rating: index + 1 });
                logging.writeWarn({ rating: index + 1 }.rating.toString());
            };
           
            scope.$watch('ratingValue', function (oldval, newval) {
                if (newval) {
                    ctrl.updateStars();
                }
            })           

        }

        public static factory(): ng.IDirectiveFactory {
       let directive: ng.IDirectiveFactory = (logfactory: app.logfactory.ILOGFactory) 
               => new StarDirective(logfactory);
            directive.$inject = ['logfactory'];
            return directive;
        }

    }

    angular.module('myapp').directive('starRating', StarDirective.factory());




CSS:

.rating {
    color: #a9a9a9;
    margin: 0;
    padding: 0;
}

ul.rating {
    display: inline-block;
}

.rating li {
    list-style-type: none;
    display: inline-block;
    padding: 1px;
    text-align: center;
    font-weight: bold;
    cursor: pointer;
}

.rating .filled {
    color: red;
}










From this post you can learn how to create a directive in Typescript



Friday, 4 November 2016

Two Way binding in Angular2

Two way data binding is the concept which makes the Angular in to the Peek position in front end development for versions 1.x, later for version 2 some of the news are reached to the users that Two way data binding is no more in Angular2, but in stable version of Angular2 we have the Two way Data Binding, Now we see the sample of Two way data binding.

The Syntax for Two way Data binding is    [(ngModel)]="propertyName"



<div class="container">
    <br />

        Height : <input type="text" [(ngModel)]="height">
        Background : <input type="text" [(ngModel)]="background">
        Class : <input type="text" [(ngModel)]="classname">
        <button type="submit" [style.height.px]="height" 
                [style.background]="background" 
                [class]="classname"            
                >Submit</button>
    </div>



In the above code you can see in each input control we are binding the value to a model using ngModel, and the model is bind to the button properties.

This alone doesnt make sense to work the ngModel in the Angular2 Applications. we have to add one more thing i.e adding FormsModule in the main module, then only ngModel will work.


import { FormsModule } from '@angular/forms';





    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppLoadComponent } from './app.load.component'
    import { UserRoutingModule } from './Routing/user.routing.module';
  
    @NgModule({
        imports: [BrowserModule,HttpModule,FormsModule,AppRoutingModule],
        exports: [],
        declarations: [AppLoadComponent],
        providers:[],
        bootstrap:[AppLoadComponent]
    })
    export class AppModule { 

    }






From this post you can learn how to do the Two way Data Binding in the Angular2 Applications.











Tuesday, 1 November 2016

Routing concepts in Angular2

In this post we are going to see how to configure the routing in Angular2 applications, in previous versions we are used the ngRoute and UiRouter concepts to configure the Route, it is almost similar to that , but we are using here the Module system to configure the Routes.

import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [
  { path: 'rating', component: webformComponent },
  { path: 'news',component:NewsComponent},
  { path: '', component:webformComponent },
  { path: '**', component:UnknownComponent }
];


export const routedComponents = [AppComponent, webformComponent,
     NewsComponent,PrintComponent,UnknownComponent];


@NgModule({
  imports : [CommonModule,RouterModule.forRoot(routes)],
  declarations:routedComponents,
  exports: [RouterModule,EditorModule,CommonModule],
})

export class AppRoutingModule { }


From the above code you can see that the RouterModule and Routes are used to configure the Routes.

We have to give the path and component which have to load for that url, here you can see the RouterModule.forRoot is used to load the routes , in overall applications we should have only one root route, others are must be child, because it is defines that is already defines and creates, so we dont need to create again and again, Here you can see the path is given as empty that means default routing, another one you can see is '**' that specifies the path whatever may be other than configured is routed to unknown component., Now this is the root component for Router module which is stored in separate file, so we have to configure or add this to main module, so we are configure the RouterModule to be exports , then only it can be import or can be used in another module.


Now we will define another set of routing which is separate from this , in this sample we are configuring and separating the routes based on module.


  import { NgModule } from '@angular/core';
  import { CommonModule} from '@angular/common'
  import { FormsModule } from '@angular/forms';
  import { Routes, RouterModule } from '@angular/router';
  import { EmployeeComponent,StudentComponent } from './employee.component'
  import { EmployeeDetailComponent } from './employee.detail'
  import { EmployeeDetailGuard } from './employeeDetailGuard';
  import { EmployeeResolver } from './employeeDetailResolve'
  import { EmployeeFilterPipe } from './employeePipe'

  const routes: Routes = [ 
    { path: 'employee',component:EmployeeComponent},
    { path: 'employee/:id',component:EmployeeDetailComponent, 
                canActivate:[EmployeeDetailGuard],
                resolve:{ userinfo:EmployeeResolver }},
    { path: 'student',component:StudentComponent},  
  ];

  export const routedComponents = [EmployeeComponent,StudentComponent,
  EmployeeDetailComponent,EmployeeFilterPipe];

  @NgModule({
    imports : [CommonModule,FormsModule, RouterModule.forChild(routes)],
    declarations:routedComponents,
    providers:[EmployeeDetailGuard,EmployeeResolver],
    exports: [RouterModule,FormsModule],
  })

  export class UserRoutingModule { }


Now we have to import both the module system in the main module which loads the application, in the above sample you can see the route is configure as ForChild, this is because we have to configure the routes as Root for only one time,
Finally we are going to import the both the things in Main module, in the above code you can see the CanActivate and Resolve properties in routes , we will discuss about this things in later posts.

import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
        
    import { FocusedDirective } from './directives/onload.directive';
    import { FocusOnLoadDirective,RgMultilineEllipses } from './directives/onload.directive';
    import { FormComponent } from './Forms/form.component';
    import { BaseRequestOptions, Http, Headers } from '@angular/http';
    import { webformComponent } from './Component/web.component'
    
    import { AppLoadComponent } from './app.load.component'

    
    import { DataService } from './data.service';
    import { AppRoutingModule } from './app.routing.module'
    import { UserRoutingModule } from './user.routing.module';
  
    @NgModule({
        imports: [BrowserModule,HttpModule,UserRoutingModule,AppRoutingModule],
        exports: [],
        declarations: [AppLoadComponent,FormComponent,FocusedDirective,
                 RgMultilineEllipses],
        providers:[DataService],
        bootstrap:[AppLoadComponent]
    })
    export class AppModule { 

    }


In the module you can see that the both the Router module are imported, Main module loads the both the routes because the router module is exported in both modules,Now we will see how to configure the router links and containers


<div>
    <nav class="navbar navbar-fixed-top navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header">   
                
                <button type="button" class="navbar-toggle collapsed" 
                      data-toggle="collapse" 
                    data-target="#angular-collapse-menu" 
                    aria-expanded="false">
                    <span class="sr-only">Toggle Navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                                             
                <a class="navbar-brand" href="#">Angular 2</a>
            </div>
            <div class="collapse navbar-collapse" id="angular-collapse-menu">
                <ul class="nav navbar-nav">                    
                        <li>
                            <a [routerLink]="['/employee']">Employees</a>
                        </li>
                        <li>
                            <a [routerLink]="['/student']">Student</a>
                        </li>
                        <li>
                            <a [routerLink]="['/rating']">Rating</a>
                        </li>
                        <li>
                            <a [routerLink]="['/news']">News</a>  
                        </li>
                    </ul>
            </div>
            
        </div>                        
    </nav>    
</div>
<div style="padding-top:65px;">
    <router-outlet></router-outlet>
</div>



that's it everything is configured, [routerLink]="['/news']"  is used to create a router link which will call the path /news and NewsComponent instance is created,  <router-outlet> </router-outlet>  is used to inject the view in the container we will load the applications, Let we see the output.


























From this post you can see how to configure the Routes and RoutesModule for the Angular2 Applications.