Posts

Showing posts with the label Angular2 Forms

Angular 2 NgModelChange Old Value

Answer : This might work (ngModelChange)="onModelChange(oldVal, $event); oldVal = $event;" or (ngModelChange)="onModelChange($event)" oldValue:string; onModelChange(event) { if(this.oldValue != event) { ... } this.oldValue = event; } Just for the future we need to observe that [(ngModel)]="hero.name" is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event". So if we de-sugar code we would end up with: <select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event"> or <[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()"> If you inspect the above code you will notice that we end up with 2 ngModelChange events and those need to be executed in some order. Summing up: If you place ngModelChange befor...

Angular 2 Custom Validator That Depends On Another Form Control

Answer : You are one step closer. You need to attach your custom validator to the FormGroup instead, because it needs to know two FormControl ( categories and mealTypes ), so attaching to FormGroup will give the validator more broad view and access to the entire FormControl To achieve that, change your ngOnInit to ngOnInit() { this.findForm = new FormGroup({ mealTypes : new FormControl(null, Validators.Required), categories : new FormControl(null) // others form control here }, validateMealType); // <-- see here is your custom function } On above code, you actually have to use FormGroup constructor instead of FormBuilder , so you can attach your custom validation in the parameters. Also, move your custom validator outside the component class. Take a look at this Plunker to get more insight for your specific case here. The solution proposed by @Michael worked for me with a minor change for the Angular 4. In the validation function...