12

在 Angular 2 表单中,尝试通过 ngSubmit 获取数据。我可以毫无问题地在我的表单组件中分配 ngModel 和 ngControl 属性,但是在子组件 MyInput 中,我无法在没有“无提供程序错误”的情况下分配 ngControl。Plunker 在这里http://plnkr.co/edit/LauhEz6vMaEmIg0hceoj?p=preview

    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES, MyInput],
template: ` <div>
                <form #hf="ngForm" (ngSubmit)="onSubmit(hf.value)">
                    <div>
                      In Form: <input type='text' [ngControl]="inform" [(ngModel)]="theValue" [required]="req" #spy >
                      <br>Classes: {{spy.className}}
                      <br>
                      <br>In Component: <my-input [props]='prop'></my-input>
                      <br>In Component: <my-input [props]='prop2'></my-input>
                    </div>
                    <button type="submit" [hidden] = "!editing">Save</button>
                    <button type="button" (click)="cancelClick()" [hidden] = "!editing">Cancel</button>
                    <button type="button" (click)="setEdit(true)" [hidden] = "editing">Edit</button>
                </form>
                Form Values {{data}}
           </div>
            `

子组件模板:

@Component({
selector: 'my-input',
directives: [FORM_DIRECTIVES],
template: ` 
            <input type='text'
              [(ngModel)]="props.Value"

如果我添加这个错误

 [ngControl]="props.id"  

我需要从表单传递给子组件吗?

4

2 回答 2

1

在 ngControl 绑定/执行时 prop 不可用不是问题吗...如果您在组件中提供了一个默认控件,然后引用当时执行的那个控件怎么propsngOnChange?当道具真的可用时。

于 2016-04-01T08:52:01.930 回答
0

更新:使用此方法,父表单不具备根据子组件的有效性确定其有效性的开箱即用能力。

作为一种解决方法,您可以尝试将子组件包装在其自己的表单元素中。

@Component({
  selector: 'my-input',
  directives: [FORM_DIRECTIVES],
  template: ` 
      <form> <--------------
        <input type='text'
          [(ngModel)]="props.Value"
          [ngControl]="props.id"  />
      </form>

不理想,但这是我可以在不使用动态表单的情况下用子组件组成表单的唯一方法https://angular.io/docs/ts/latest/cookbook/dynamic-form.html

于 2016-05-12T07:10:17.810 回答