2017-09-15 20 views
0

在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

+0

可以創建plunker? –

+0

https://plnkr.co/edit/rDluyJduyHF7vclK9wRE?p=preview – mrshickadance

+0

您需要爲'test-component'組件實現'ControlValueAccessor'。請參閱[在Angular表單中實現ControlValueAccessor時再也不會混淆](https://blog.angularindepth.com/never-again-be-confused-when-implementing-controlvalueaccessor-when-imple-forms-93b9eee9ee83)。在閱讀文章 –

回答

2

你可以試試這個,看看它是否工作,

子組件

@Output() childControl = new EventEmitter<NgModel>(); // import { NgModel } from '@angular/forms'; 
@ViewChild('myControl') myControl: NgModel; 

ngAfterViewInit() { 
this.childControl.emit(myControl); // emitting the control to the parent to be picked up there and added to the main form 
} 

子模板

<input #myControl="ngModel" class="text-input" [name]="formInputName" [id]="formInputName" type="text" [(ngModel)]="searchValue" 
      (change)="onChange(searchValue)" 
      (blur)="onBlur()" 
      (focus)="onFocus()" 
      [required]="isRequired"> 

父模板

<child-component (childControl)="childControlReady($event)"></child-component> 

父組件

childControlReady(control: NgModel) { 
this.testform.addControl(control); 
} 
+1

之後,您可以編輯您的問題以添加一些說明,非常好,謝謝! #myControl給了我ngModel的參考是關鍵。 – mrshickadance

相關問題