我想要一个包含标签和文本框的模板.此模板可以在我的页面的不同位置重复使用.做到这一点,我创建了一个MyTextComponent.我想知道如何将不同的值绑定到组件输入.
例如:
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; }
MyPageComponent
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); } }
你的myText缺少一个@Output()
import {Component,Output} from 'angular2/core'; @Component({ selector: 'myText',template:`<label>{{someLabel}}</label> <input id=myId type="text" [ngModel]=bindModelData (ngModelChange)="updateData($event)"> ` }) export class MyTextComponent { @Input() myId : string; @Input() bindModelData: any; // note that this must be named as the input name + "Change" @Output() bindModelDataChange: any = new EventEmitter(); updateData(event) { this.bindModelData = event; this.bindModelDataChange.emit(event); } }
那么你可以使用它
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; }