所以这是我的父表格:
<form [ngFormModel]="formModel"> <ui-form-control *ngFor="#key of controlsKeys" [control]="formModel.controls[key]" [name]="key"> </ui-form-control> </form>
这是我的组件:
@Component({ selector: 'ui-form-control' }) @View({ template: ` <label>{{name}}: </label> <input [ngFormControl]="control" [placeholder]="name"> `,directives: [FORM_DIRECTIVES] }) export class UiFormControl{ @Input() control: UiControl; @Input() name: string; constructor(){ } }
我可以在我的ui-form-component中看到Control值,但是当我更改它时,formModel-ComponentGroup不会更新.所以看起来双向绑定在这里不起作用.
实际上,如果我删除我的< ui-form-control>并放置简单< input>而不是它将工作,formModel将按预期更新.
解决方法
我认为您应该在子组件中使用@Input和@Output进行双向绑定.后者被通知父组件控件在子组件内发生变化.我想到这样的事情:
@Component({ selector: 'ui-form-control' template: ` <label>{{name}}: </label> <input [ngFormControl]="control" (change)="inputChanged()" [placeholder]="name"> `,directives: [FORM_DIRECTIVES] }) export class UiFormControl{ @Input() control: UiControl; @Output() controlChange: EventEmitter; @Input() name: string; constructor(){ this.controlChange = new EventEmitter(); } inputChanged() { this.controlChange.emit(this.control); } }
我通过利用ng-content对我的表单领域使用了一种中间方法.
@Component({ selector: 'field',template: ` <div class="form-group form-group-sm" [ngClass]="{'has-error':control && !control.valid}"> <label for="for" class="col-sm-3 control-label">{{label}}</label> <div #content class="col-sm-8"> <ng-content ></ng-content> <span *ngIf="control && !control.valid" class="help-block text-danger"> <span *ngIf="control?.errors?.required">The field is required</span> </span> </div> </div> ` }) export class FormFieldComponent { @Input() label: string; @Input() state: Control; }
它在父组件中的使用:
<form [ngFormModel]="companyForm"> <field label="Name" [state]="companyForm.controls.name"> <input [ngFormControl]="companyForm.controls.name" [(ngModel)]="company.name"/> {{name.valid}} </field> </form>
这样,输入,选择,textareas仍然在父组件内进行管理,但是字段组件处理字段格式(例如Bootstrap3的结构)并利用控件来显示错误(如果有的话).这样你就不再需要双向绑定对于field组件而后者更通用了;-)
希望它能帮到你,蒂埃里