2016-04-11 35 views
1

我想要使用Angular2(使用TypeScript和Jade)實現自定義表單。得到「沒有提供者例外」把ngControl的子組件

當我用my-input元素我自定義表單組件,而不是input創建並添加ngControl指令input,我得到異常錯誤「無提供ControlContainer!」。然後,當我從input元素中刪除ngControl時,沒有發生錯誤,但表單函數不起作用(例如驗證器)。

父組件

@Component({ 
    selector: 'top-page', 
    template: ` 
    <form [ngFormModel]="myForm"> 
     <my-input name="username" placeholder="username is here."> 
    </form> 
    `, 
}); 
export class TopPageComponent { ... } 

副組分

@Component({ 
    selector: 'my-input', 
    template: ` 
    <label class="custom-class-1"> 
     <div class="custom-class-2"></div> 
     <input type="text" id="{{name}}" placeholder="{{placeholder}}" ngControl="{{name}}" [(ngModel)]="{{name}}"> 
    </label> 
    `, 
}); 
export class MyInputComponent { ... } 

受審,我追加ngControlGroup指令label元素my-input成分,但得到的錯誤。 (當然,在打字稿文件中寫道import Component, Input, etc...@Input()。)

回答

1

我認爲你應該把一個表單標籤到您的子組件:

<form> 
    <label class="custom-class-1"> 
    <div class="custom-class-2"></div> 
     <input type="text" id="{{name}}" 
      placeholder="{{placeholder}}" 
      ngControl="{{name}}" [(ngModel)]="{{name}}"> 
    </label> 
</form> 
+0

謝謝。獲取沒有錯誤,但表單功能不起作用... –

+0

這取決於你想要做什麼。您的子組件不能參與到父組件的表單中。有一些工作要做;-)請參閱此鏈接瞭解更多詳情:http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/。在「NgModel兼容組件」一節中, –

相關問題