在Angular 2中,我有一個包含輸入的子組件。我想將此輸入(控件)添加到父組件窗體(NgForm)。Angular添加控件以從子組件中形成
爲了簡單起見,我目前使用的是模板驅動表單。
我看到這個答案,但認爲這很可能過時?:Angular 2 Add control to parent component's form
子組件模板: formInputName是輸入綁定,這樣我可以重複使用這個組件,並動態添加「名」屬性。
<input class="text-input" [name]="formInputName" [id]="formInputName" type="text" [(ngModel)]="searchValue"
(change)="onChange(searchValue)"
(blur)="onBlur()"
(focus)="onFocus()"
[required]="isRequired">
在父組件我有形式的實例:
@ViewChild('testForm') testForm: NgForm;
我怎麼能子組件控件添加到NgForm這種情況?我不知道如何處理addControl。不知道我需要在模板中添加什麼,或者如何以編程方式在控制器中執行此操作。
Plunker:https://plnkr.co/edit/rDluyJduyHF7vclK9wRE?p=preview
可以創建plunker? –
https://plnkr.co/edit/rDluyJduyHF7vclK9wRE?p=preview – mrshickadance
您需要爲'test-component'組件實現'ControlValueAccessor'。請參閱[在Angular表單中實現ControlValueAccessor時再也不會混淆](https://blog.angularindepth.com/never-again-be-confused-when-implementing-controlvalueaccessor-when-imple-forms-93b9eee9ee83)。在閱讀文章 –