我尝试了反应式表单valueChanges但valueChanges方法不返回已更改的输入字段名称。
我认为代码是这样的。但我认为这不是聪明的方式。因为我必须比较每个输入字段。所以我需要更聪明的方式。
// get init view data from local storage
this.localstorageService.getPlaceDetail().subscribe(data => {
this.initPlaceDetail = data;
// watch changed value
this.editPlaceForm.valueChanges.subscribe(chengedVal => {
if (chengedVal['ja_name'] !== this.initPlaceDetail.languages.ja.name.text) {
this.changedJA = true;
}
if (chengedVal['ja_romaji'] !== this.initPlaceDetail.languages.ja.name.romaji) {
this.changedJA = true;
}
// ...... I have to check all input fields??
});
});
答案 0 :(得分:1)
我正在从数组中添加表单控件,类似的东西对我有用。只是引用您需要的项目,而不是期望valueChanges可以将其传递给您。
myFields.forEach(item => {
const field = new FormControl("");
field.setValue(item.value);
field.valueChanges.subscribe(v => {
console.log(item.name + " is now " + v);
});
});
答案 1 :(得分:1)
这是我获取表单控制权的方法。
我为关心的人分享了
获取列表控件更改值的方法
private getChangedProperties(form): any[] {
let changedProperties = [];
Object.keys(form.controls).forEach((name) => {
let currentControl = form.controls[name];
if (currentControl.dirty)
changedProperties.push({ name: name, value: currentControl.value });
});
return changedProperties;
}
如果您只想获得最新更改的控件,则可以使用
var changedProps = this.getChangedProperties(this.ngForm.form);
var latestChanged = changedProps.reduce((acc, item) => {
if (this.changedProps.find(c => c.name == item.name && c.value == item.value) == undefined) {
acc.push(item);
}
return acc;
}, []);
答案 2 :(得分:-1)
您可以收听每个表单控件的值更改事件,而不是收听整个表单更改,如下面的代码所示:
this.myForm.get('ja_name').valueChanges.subscribe(val => {
this.formattedMessage = `My name is ${val}.`;
});