我想要一个由标签和文本框组成的模板。这个模板可以在我页面的不同地方重复使用。为此,我创建了一个 MyTextComponent。我想知道如何将不同的值绑定到组件输入。
例如:
我的文本组件
import {Component, Input} from 'angular2/core';
@Component({
selector: 'myText',
template:`<label>{{someLabel}}</label>
<input id=myId type="text" [(ngModel)]=bindModelData>
`
})
export class MyTextComponent {
@Input() myId : string;
@Input() bindModelData: any;
}
我的页面组件
import {Component} from 'angular2/core';
import {MyTextComponent} from './MyTextComponent.component'
@Component({
template:`<myText myId="id1" bindModelData="myString1"></myText>
<myText myId="id2" bindModelData="myString2"></myText>
`,
directives:[MyTextComponent]
})
export class MyPageComponent{
myString1: string;
myString2: string;
}
如何将 MyTextComponent 输入的 ngModel 绑定到 MyPageComponent 局部变量?
编辑:在添加@Output 后尝试,但它没有工作:( MyPageComponent 中的插值是空白的,并且日志打印未定义。但是插值适用于 mytextComponent。任何想法
import {Component} from 'angular2/core';
import {MyTextComponent} from './myText.component'
@Component({
template:`<myText myId="id1" [(bindModelData)]="myString1"></myText>
<myText myId="id2" [(bindModelData)]="myString2"></myText>
{{myString1}}
{{myString2}}
<button (click)="clicked()">Click Me</button>
`,
directives:[MyTextComponent],
selector:'myPage'
})
export class MyPageComponent{
myString1: string;
myString2: string;
clicked(){
console.log(this.myString1+'--'+this.myString2);
}
}
import {Component,Input,Output,EventEmitter} from 'angular2/core';
@Component({
selector: 'myText',
template:`<label>{{someLabel}}</label>
<input id=myId type="text" [ngModel]=bindModelData (ngModelChange)="updateData($event)">
modeldata - {{bindModelData}}
`
})
export class MyTextComponent {
@Input() myId : string;
@Input() bindModelData: any;
@Output() bindModelDataChanged: any = new EventEmitter();
updateData(event) {
console.log('some random text');
this.bindModelData = event;
this.bindModelDataChanged.emit(event);
}
}