2017-08-05 115 views
0

我已經創建了以下自定義按鈕組件。點擊這個按鈕我想重置表單。但是當我執行點擊操作時,出現錯誤:@功能的輸入綁定

"ERROR TypeError: Cannot read property 'reset' of undefined"

(因爲重置是功能)。

請幫我理解我的錯誤。

以下是我的代碼自定義組件代碼

@Input() clearFormData: any; 

<button *ngIf="cancelRequired" type="button" class="btn btn-warning pull-right" 
     (click)="clearFormData()" style="margin-left:0.3em">Cancel</button> 

我使用上述組件這樣

import { Component, OnInit } from '@angular/core'; 
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms'; 

@Component({ 
    selector: 'app-model-driven', 
    template: '<form-actions [clearFormData] ="clearForm"></form-actions>', 
    styleUrls: ['./model-driven.component.css'] 
}) 
export class ModelDrivenComponent implements OnInit { 
    clearForm() { 
    this.form.reset(); 
    } 

回答

0

您需要在您的自定義組件聲明輸出,並在另一個這樣的處理:

自定義組件的HTML文件:

<button *ngIf="cancelRequired" type="button" class="btn btn-warning pull-right" 
    (click)="clearFormData()" style="margin-left:0.3em">Cancel</button> 

定製元件打印稿文件:

@Output() onReset:EventEmitter<string> = new EventEmitter<string>(); 

clearFormData(){ 
    this.onReset.emit(''); 
} 

您可以使用它像這樣:

import { Component, OnInit } from '@angular/core'; 
import { FormGroup, FormControl, FormBuilder, Validators } from 
'@angular/forms'; 

@Component({ 
    selector: 'app-model-driven', 
    template: '<form-actions (onReset) ="clearForm($event)"></form-actions>', 
    styleUrls: ['./model-driven.component.css'] 
}) 
export class ModelDrivenComponent implements OnInit { 
    clearForm() { 
     this.form.reset(); 
    } 
} 

其中這裏的$事件是我們在發射功能,這是不是在你的情況下有用通過了它的價值。

我的自定義組件中可以有多個@output嗎? 如果我的自定義組件有多個按鈕,我可以這樣做嗎?

@Output() onBack: EventEmitter<string> = new EventEmitter<string>(); 

    backPage() { 
    this.onBack.emit(''); 
    } 

<form-actions [cancelRequired]="true" 
    (onReset)="clearForm()" (onBack)="backPageCalled()"></form-actions> 
+0

如果我有多個按鈕讓我們說「編輯」,我想在我的formaction組件中使用它,我可以這樣做嗎? 像這樣? – hemantmali

+0

是的,你可以輸出無限數量的事件發射器(但當然它就像函數的參數,你猜不應該輸出超過3,4個事件)。 – Nour

0

您需要綁定的功能方面給母公司組件類,例如:

constructor(){ 
    this.clearForm = this.clearForm.bind(this); 
} 

現在你可以通過clearForm函數在別的地方它的執行上下文將保留在你傳遞它的類中。

但是,對於這種操作,我建議寧願使用子組件中的@Output。例如

(clearFormData)="this.form.reset()" 

然後在組件的清除按鈕

(click)="this.clearFormData.emit()"