Mahesh K Mahesh K - 4 months ago 21
HTML Question

Binding a value from custom control to html control using angular 2 directives in typescript

I have created a custom control directive as "my-text-box", inside this directive I am using html control , I need to pass values from my custom control to html input control. In angular1 simply I am using like

<my-text-box id="1" name="Box 1">
using my custom attributes of scope variables in directive, i assigned the values to html control like
<input type="text" id="{{id}}" name={{name}} >
how can i use this scenario in angular 2.

Here is my sample code:

AppComponent.ts

import {Component} from '@angular/core';
import {TextBoxComponent} from './TextBoxComponentDirective';

@Component({
selector: 'my-app',
template: '<h1>{{title}}</h1> <my-text-box id="66" name="MyText1"></my-text-box>',
directives:[TextBoxComponent]
})

export class AppComponent {
title="Sample TextBox";
}


TextBoxComponentDirective.ts

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

@Component({
selector:'my-text-box',
templateUrl: './TextBoxTemplate.html',
})
export class TextBoxComponent {

@Input() id;
}


TextBoxTemplate.html

<input type="text" [name]="name" [id]="id"/>

Answer

You can use @Input() for this:

@Component({
    selector: 'my-text-box',
    template: `
        <input type="text" [id]="id" [name]="name" >
    `
})
export class MyTextBoxComponent {
    @Input() id;
    @Input() name;
}

In your parent component you now can use it like so:

<my-text-box id="1" name="Box 1">

Or if you need to bind to variables:

<my-text-box [id]="someId" [name]="theBoxName">

Working Plunker for example usage

Comments