Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger ngOnChanges

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&nbsp;</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}}&euro;</option>
    </select>
  </div>
  <div class="form-group">
    <label for="gesamtpreis">Gesamt&nbsp;</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();
  }
}
like image 337
Adder Avatar asked Jul 26 '26 03:07

Adder


1 Answers

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.

like image 69
tony Avatar answered Jul 28 '26 20:07

tony