有没有办法制作双向绑定输入组件,也可以在组件内部进行验证?
我想要实现的是拥有一个可以在我的表单中排列的组件,如下所示:
<form #f="ngForm">
<my-form-input [(inputModel)]="name" [inputField]="myFormInputName"></my-form-input>
<my-form-input [(inputModel)]="name2" [inputField]="myFormInputName2"></my-form-input>
...
<my-form-input [(inputModel)]="lastItem" [inputField]="lastItemName"></my-form-input>
</form>
我有以下设置,但不知道如何正确设置:
组件:
import {Component,Input, Output,EventEmitter} from 'angular2/core'
import {FORM_DIRECTIVES} from 'angular2/common';
@Component({
selector: 'my-form-input',
directives: [FORM_DIRECTIVES],
template:
`
<input type="text" class="form-control" id="i1" required [ngModel]="inputModel" (ngModelChange)="onChangeInput($event)" ngControl="ctrl" #ctrl="ngForm"/>
<p>{{"Is field valid? I would like to make some decisions here depending on that: "+ctrl.valid}}</p>
`
})
export class InputComponent {
constructor(){};
@Input() inputField:string;
@Input() inputModel: Object;
@Output() inputModelChange = new EventEmitter();
onChangeInput(event){
this.inputModel=event;
this.inputModelChange.emit(event);
}
}
应用程序:
//our root app component
import {Component} from 'angular2/core'
import {FORM_DIRECTIVES} from 'angular2/common';
import {InputComponent} from './my.input'
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<p>Is there a way to make a custom 2 way binding form input component having also validation?</p>
<form #f="ngForm">
<my-form-input [(inputModel)]="name" [inputField]="myFormInputName"></my-form-input>
<p>{{name}}</p>
</form>
</div>
`,
directives: [InputComponent,FORM_DIRECTIVES]
})
export class App {
constructor() {
this.name = 'Angular2'
}
}
我还做了一个 Plunker 来说明我的问题:http ://plnkr.co/edit/0vXjHbQmv7v7EKQcLWaa?p=preview