0

I am trying to figure out form validation in Angular 2. Right now I have an add product form that is adding a product to a particular store's inventory. I want to validate that the product's price is more than the wholesale price of the product, so I added the wholesale price as a data-* attribute. What I can't figure out is how to reference that attribute with Angular 2's NgControl. Here is my code:

...
<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']
    });

}
...
watzon
  • 2,401
  • 2
  • 33
  • 65
  • Why do you make it an attribute? What about creating an `@Input() wholeSale` and then access it from your code. The value will not yet be available in the `constructor() { ... }` only in `ngAfterViewInit()` – Günter Zöchbauer Mar 23 '16 at 15:59

1 Answers1

1

I would create a global validator for your form:

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

The validator_moreThanWholesale method will have all the controls as input so you will be able to check:

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

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

See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360