所以这是我的父母表格:
<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将按预期更新。
答案 0 :(得分:2)
我认为您应该在子组件中使用双向绑定@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的结构)并利用控件显示错误(如果有的话)。这样,您不再需要双向绑定字段组件,后者更通用; - )
希望它可以帮到你, 亨利
答案 1 :(得分:0)
我知道距您提出请求已经有一段时间了,但对于遇到同样问题的人来说,也许我问的AJT82遮阳篷可以帮助您: Problem with mat-select when submitting form in angular
答案 2 :(得分:-1)
你期待什么双向约束?
您可以通过将属性设置为(单向)绑定和事件来获得双向绑定。实际上还有一点点,但捷径很简单:
<input [(ng-model)]="myField" >
您可以在Victor Savkins blog了解更多信息。