2016-03-23 61 views
0

我想弄清楚Angular 2中的表單驗證。現在我有一個添加產品表單,即將產品添加到特定商店的庫存。我想驗證產品的價格是否高於產品的批發價格,因此我將批發價格添加爲data-*屬性。我無法弄清楚如何使用Angular 2的NgControl引用該屬性。這裏是我的代碼:Angular 2表單字段驗證與數據破折號屬性

... 
<div class="four wide field"> 
    <label>Wholesale Price</label> 
    <div class="ui left icon input"> 
    <input type="text" disabled [(ngModel)]="wholesalePrice" ngControl="wholesale" /> 
    <i class="dollar icon"></i> 
    </div> 
</div> 

<div class="four wide field"> 
    <label>Price</label> 
    <div class="ui left icon input"> 
    <input type="text" [(ngModel)]="retailPrice" [attr.data-wholesale]="wholesalePrice" ngControl="price" required /> 
    <i class="dollar icon"></i> 
    </div> 
</div> 
... 

... 
constructor(private fb: FormBuilder) { 

    this.form = fb.group({ 
     price: ['price', Validators.compose([ 
      Validators.required, 
      this.validator_moreThanWholesale 
     ])], 
     quantity: ['quantity'] 
    }); 

} 
... 
+0

爲什麼你把它作爲一個屬性?怎麼樣創建一個'@Input()wholeSale',然後從你的代碼中訪問它。只有在'ngAfterViewInit()'中''constructor(){...}'的值纔會有效 –

回答

1

我將創建一個全球性的驗證器爲您的表單:

this.form = fb.group({ 
    price: ['price', Validators.compose([ 
    Validators.required 
    ])], 
    quantity: ['quantity'] 
}, { 
    validator: this.validator_moreThanWholesale 
})); 

validator_moreThanWholesale方法將所有的控件輸入,這樣你就可以檢查:

validator_moreThanWholesale(group: ControlGroup) { 
    var wholesale = group.controls.wholesale.value; 
    var price = group.controls.price.value; 

    return (price < wholesale) ? { moreThanWholesale: true } : null 
} 

查看此問題了解更多詳情: