2016-11-11 124 views
2

我只是紅角2烹飪書你如何創建動態表單,但我徘徊我怎麼可以添加自定義驗證器到特定的領域。創建自定義驗證器的動態形式角2

questions.forEach(question => { 
    group[question.key] = question.required ? new FormControl(question.value || '', Validators.required) 
              : new FormControl(question.value || ''); 
}); 

在這裏,他們形成了從組,以保存表單輸入等什麼,如果我想在特定的驗證適用於某個特定問題 例如:如果我有確認密碼匹配的輸入。 我知道有validateequal屬性做這個任務我怎麼能將此validateequal甚至創建自己的自定義驗證

注意,它是動態的形式,這意味着可以容納例如我計劃使用任何輸入同樣的形式生成登錄表單,這意味着它只有密碼輸入,我需要檢查是否有輸入將保存密碼,如果有任何將保存密碼確認,如果是的話,那麼我需要檢查它們是否匹配之前提交

+0

這應該可以幫助你脫離伴侶。 https://scotch.io/tutorials/how-to-implement-a-custom-validator-directive-confirm-password-in-angular-2 就自定義驗證去,IM在同一船試圖那個。我相信定製指令將會是一條路,但我可能是錯的。 這人可能也會幫助你,有點過時,但你可以從中得到一個想法。 http://www.joshmorony.com/advanced-forms-validation-in-ionic-2/ –

+0

我紅色的所有這些文章,但我的問題是我動態建立窗體,我想驗證確認密碼輸入,但實際上在這一刻密碼控制尚未建立。 @Swank你知不知道我可以手動設置表單驗證 – kero

+0

@kero你知道嗎? – k11k2

回答

0

好吧,我想我有。

您將使用自定義指令來完成作業。

這是自定義指令https://angular.io/docs/ts/latest/guide/attribute-directives.html

如果創建但是你模板化您的應用程序,你可以很容易地修改,以適應您的參數

一個非常基本的教程。

在我的,我用以下方式使用該示例。

您的NgModule || app.module.ts

import { customDirective } from '../directive/path'; 

你customDirective.ts || JS

import {Directive, HostListener, Input, ElementRef} from '@angular/core'; 
@Directive({ 
    selector: '[fooSelector]' 
}) 

export class CustomDirective { 
    constructor(private el: ElementRef, private renderer: Renderer) {} 
    @Input('fooSelector') testing: Object; 

    //this controls event type with change being the event 
    @HostListener('change') onChange(){ 
    this.logicFunct(this.htmlAttr); //will define htmlAttr in template 
    } 

    //this is the validator logic 
    private logicFunct($obj: Object){ 
    // submit logic here - for ex: 
    if($obj != 'test) { 
     this.varBar = true; //check template ngIf 
    } 
    } 
} 

模板

<input 
    type="text" 
    #htmlAttr 
    [fooSelector]="this.htmlAttr._value" 
    *ngIf="!this.varBar"> 
</input> 

,我幾乎可以肯定有其他更好的的方式來做到這一點,如果有人有一個,請告訴我們!

希望這可以幫助任何人絆倒它。

+0

謝謝你的貢獻我真的很感激,但我的問題是完全不同的, – kero

+0

好吧,它是,它不是。雖然這有點不正統,但您可以將此方法用於您的自定義驗證。 –

+0

我的實際問題是,如果此輸入字段存在,我需要從另一個輸入中獲取值,請檢查我的更新以上是否存在問題 – kero