如何在组件中的窗体上触发ngOnChanges?
我想计算一个新的总价格(gesamtpreis),每当任何形式的输入改变。
我看了其他的答案,但这只是使我的代码更奇怪,而不是工作。我是否需要@输入,它是否正确连接。
组件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>组件代码:
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();
}
}发布于 2022-06-08 13:33:00
ngModel
为什么要确切地使用ngOnChanges?
您只需使用ngModel绑定到模板表单中的值:
<select name="extra1" class="btn btn-secondary dropdown-toggle" [ngModel]="gesamtpreis">如果您希望在值更改时触发其他逻辑,则只需为该值创建getter和setter:
private _gesamtpreis = 'kein Preis';
get gesamtpreis() {
return this._gesamtpreis
}
set gesamtpreis(value) {
this._gesamtpreis = value
/* Some other logic goes here... */
/* You could event push to a subject here, whatever floats your boat... */
}绑定到(更改)事件
<form #carConfigurationForm="ngForm" (change)="formChanged(carConfigurationForm)">剧本:
formChanged(event) {
console.log(event.value)
}在您的情况下,您甚至不需要将表单引用传递到函数中。因为你似乎只想得到一些通知的形式被改变。
这是一个供你玩的斯塔克布利茨。
发布于 2022-06-08 14:16:05
ngOnChanges不会被触发,因为它用于接收@Input的组件。它是一个生命周期挂钩,当绑定到某个组件的@input被更改或重置时会被触发。
即使您的组件绑定了一些input,您也无法检测到表单上的更改,因为表单是组件的原生dom元素,因此无法通过输入接收它。
ngOnChanges只对通过input接收的数据执行更改检查。
为此,您可以订阅Form.valueChanges。
发布于 2022-06-08 13:08:39
窗体拥有可以订阅的属性valueChanges。
你可以
// declare the variable referencing the ngForm
@ViewChild('carConfigurationForm') carConfigurationForm: NgForm;
selectedExtra: Extra[] = [];然后
ngOnInit() {
this.getSelectedExtra();
this.carConfigurationForm.form.valueChanges.subscribe((newValue: any) => {
console.log('old value:', carConfigurationForm.form.value);
console.log('new value:', newValue);
});
}https://stackoverflow.com/questions/72545798
复制相似问题