【问题标题】:Binding a value from custom control to html control using angular 2 directives in typescript使用打字稿中的角度2指令将值从自定义控件绑定到html控件
【发布时间】:2016-12-03 21:52:30
【问题描述】:

我创建了一个自定义控件指令作为“my-text-box”,在这个指令中我使用 html 控件<input>,我需要将值从我的自定义控件传递到 html 输入控件。在 Angular1 中,我只是在使用 <my-text-box id="1" name="Box 1"> 之类的指令,在指令中使用范围变量的自定义属性,我将值分配给 html 控件,例如 <input type="text" id="{{id}}" name={{name}} > 我如何在 Angular 2 中使用这种场景。

这是我的示例代码:

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"/>

【问题讨论】:

  • 在 angular2 中,指令没有 Angular1 中的模板元属性。所以需要代码并向我们展示您到目前为止所做的工作。
  • @micronyks 更新

标签: html typescript angular angular2-directives


【解决方案1】:

您可以为此使用@Input()

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

在您的父组件中,您现在可以像这样使用它:

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

或者如果你需要绑定到变量:

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

工作Plunker 示例用法

【讨论】:

  • 我试过你的例子,但它在输入控件中显示 id="undefined" name="undefined"。查看我的示例代码
  • 你可以试试&lt;my-text-box [id]="'66'" [name]="'MyText1'"&gt;&lt;/my-text-box&gt;,在字符串周围加上'
  • 我检查了Plunker,它工作得很好。
  • 是的,我已经看到了,但在这种情况下,您使用了单个 ts 文件。但我这边我需要使用单独的应用程序和指令文件。这样我就可以重用这个指令..
  • 这应该没什么区别,但我可以把它分开来供您欣赏。
猜你喜欢
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
相关资源
最近更新 更多