Mahesh K Mahesh K - 1 year ago 98
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:


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

selector: 'my-app',
template: '<h1>{{title}}</h1> <my-text-box id="66" name="MyText1"></my-text-box>',

export class AppComponent {
title="Sample TextBox";


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

templateUrl: './TextBoxTemplate.html',
export class TextBoxComponent {

@Input() id;


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

Answer Source

You can use @Input() for this:

    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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download