How to trigger ngOnChanges on a form in a component?
I want to calculate a new total price (gesamtpreis) whenever any form input changes.
I looked at other answers, but this just made my code more weird instead of working. Do I need the @Input and is it correctly wired.
component HTML:
<div class="card my-5">
<div class="card-body">
<form #carConfigurationForm="ngForm" ng-change="ngOnChanges">
<div class="form-group">
<label for="extra">Extra 1 </label>
<select name="extra1" class="btn btn-secondary dropdown-toggle">
<option value="default">Kein Extra</option>
<option *ngFor="let extra of selectExtra" [value]="extra.name">{{extra.name}} {{extra.preis}}€</option>
</select>
</div>
<div class="form-group">
<label for="gesamtpreis">Gesamt </label>
<span name="gesamtpreis" [innerHTML]="gesamtpreis"></span>
</div>
</form>
component code:
import { Component, OnInit, OnChanges, Input } from '@angular/core';
import { Extra } from '../model/extra';
import { ExtraService} from '../service/extra.service';
import { SimpleChanges } from '@angular/core';
@Component({
selector: 'app-car-configuration-form',
templateUrl: './car-configuration-form.component.html',
styleUrls: ['./car-configuration-form.component.sass']
})
export class CarConfigurationFormComponent implements OnInit, OnChanges {
selectExtra : Extra[] = [];
gesamtpreis : string = 'kein Preis';
constructor(private extraService: ExtraService) { }
getSelectedExtra(): void{
this.extraService.findAll()
.subscribe(selectExtra => this.selectExtra= selectExtra);
}
ngOnInit() {
this.getSelectedExtra();
}
@Input() extra1: string = '';
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
console.log('zzz ngOnChanges');
this.gesamtpreis = "zzz"; //changes.toString();
}
}
ngOnChanges is not triggered because it is meant for component that recieves @Input. It is a life cycle hook that gets triggered when @input binded to some component is changed or reset.
Even if your component had some input binded, you wouldn't be able to detect changes on form, because form is a native dom element for your component, you don't receive it via input.
ngOnChanges performs change check only on the data that is recieved via input
You can subscribe to Form.valueChanges for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With