0
votes

I have a domain model for bank account:

export interface BankAccount { acc1: string, acc2: string, acc3: string, acc4: string }

Parent form is template-driven, captures name and bank account number. To capture bank account number which is comprised of 4 parts digits, I managed to write a custom form control component in model-driven way. It implements ControlValueAccessor and Validator interfaces so, on a parent form, its value/valid works perfect.

Now I tried to write another bank account component in template-driven way. So far its ControlValueAccessor interface seems working but I couldn't make its Validator interface to work.

The problem is: In account 1, its value is emitted ok to parent form and validated each time I types in any number. But in account 2, the value is emitted ok but for some reason, validate() method is not being called???

This plunker

1

1 Answers

1
votes

In your second component you have to fire propagateChange method manually to invoke the validation.

Template

<input type="text" name="acc1" [ngModel]="accountNumber.acc1"
    (ngModelChange)="change('acc1', $event)"/>

or

<input *ngFor="let prop of ['acc1', 'acc2', 'acc3', 'acc4']" type="text" 
   name="{{prop}}" [ngModel]="accountNumber[prop]" 
          (ngModelChange)="change(prop, $event)"/>

Component

change(prop, val) {
  this.accountNumber[prop] = val; 
  this.propagateChange(this.accountNumber);
}

Note: i fixed your typo in propogateChange method

Updated Plunker Example

See also a great article about it: