2016-09-21 74 views
1

我正在使用Angular2。我有這個在我的主機部件:跨多個組件的表單驗證

<form #f="ngForm" novalidate (ngSubmit)="save()"> 
    <child [cosField]="cosField" [f]="f"></child> 
    <button type="submit" [disabled]="!f.valid">Submit</button> 
</form> 

我有不同的子組件,我從這個組件調用。 在子組件的代碼是:

<input type="text" name="flow" [(ngModel)]="cosField.value" required #name="ngModel"/> 
<div [hidden]="name.valid || (!f.submitted)" 
    class="error"> 
    An error has occurred. 
</div> 

我要訪問此局部變量f的子組件。基本上用於表單驗證。如果子組件中的某些驗證失敗,則顯示「發生錯誤」消息。但在主組件中,f.valid仍然保持爲真,因此始終啓用提交按鈕。但是,如果我將子組件內聯到主組件中,則一切正常,如果驗證失敗,則提交按鈕將被禁用。 是否有辦法將表單分割爲多個組件,並且仍然能夠使用局部變量f有效地驗證控件?

回答

0

使用Angular2將值傳出子組件,因此父組件可以捕獲事件並更新其對f的有效感。

您必須添加到您的父組件和子組件的組件邏輯。在打字稿模式看起來是這樣的:

父組件:

...<imports>... 
@Component({ 
    selector: 'parent-component', 
    ... 
}) 
export class ParentComponent implements OnInit { 
    ... 
    ngOnInit() { 
     ... 
    }); 

    childChanged(event) { 
     // Use event value to do validity checking here. 
    } 
} 

子組件:

import { Component, Output, EventEmitter } from '@angular/core'; 
<...other imports...> 

@Component({ 
    selector: 'child', 
    ... 
}) 
export class ChildComponent implements OnInit { 
    @Output() change: EventEmitter<any> = new EventEmitter(); 

    ... 
} 

現在你的孩子的input可以在@Output發出事件,傳播給父母。例如,孩子可以傳播上模糊變化,並傳遞的name有效性:

<input type="text" name="flow" [(ngModel)]="cosField.value" required #name="ngModel" (blur)="change.emit(name.valid)" /> 

父拿起變化,並通過尋找您的自定義change事件處理有效性狀態:

<child [cosField]="cosField" [f]="f" (change)="childChanged($event)"></child> 

這裏有其它文獻,我發現有用的,當第一次學習這個東西: