2016-03-23 35 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 
} 

查看此问题了解更多详情: