组件内部形式为Angular 2

所以这是我的父表格:

<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组件而后者更通用了;-)

希望它能帮到你,蒂埃里

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...