У меня действительно странная проблема.У меня есть несколько экземпляров компонента с почти одинаковыми свойствами ввода.Один из них (первый компонент 'doc-Diagnose-form' в приведенном ниже коде) игнорируется при изменении одного из входных свойств.Все остальные экземпляры компонентов (созданные с помощью * ngFor) уничтожаются и создаются заново при изменении одного из входных свойств.Как это может произойти?
Информация: Я использую Angular 6
Родительский компонент .html:
// Component that is not changed
<doc-diagnose-form [pc]="pc" [diagnose]="pc.pdx"
(onChangeDiagnose)="changeDiagnose($event)" (onDeleteDiagnose)="deleteDiagnose($event)">
</doc-diagnose-form>
// Components that become updated
<doc-diagnose-form [pc]="pc" [diagnose]="diagnose" *ngFor="let diagnose of pc.diagnoses"
(onChangeDiagnose)="changeDiagnose($event)" (onDeleteDiagnose)="deleteDiagnose($event)">
</doc-diagnose-form>
Родительский компонент .ts
import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { Diagnose, DiagnoseArray, PatientCase, PrimaryDiagnoseArray } from '../../../models/models';
@Component({
selector: 'doc-diagnose-list',
templateUrl: './diagnose-list.component.html',
styleUrls: ['./diagnose-list.component.css']
})
export class DiagnoseListComponent implements OnInit, OnChanges {
@Input() diagnoses?: DiagnoseArray;
@Input() pc?: PatientCase;
@Input() primaryDiagnoses?: PrimaryDiagnoseArray;
@Output() addCoding = new EventEmitter();
@Output() modifyDiagnose = new EventEmitter();
@Output() removeDiagnose = new EventEmitter();
constructor() { }
ngOnInit() {}
ngOnChanges(changes: SimpleChanges) {
console.log('OnChanges: ', changes);
}
changeDiagnose(value): void {
this.modifyDiagnose.emit(value);
}
deleteDiagnose(value): void {
this.removeDiagnose.emit(value);
}
}
Буду рад, если кто-нибудь сможет мне помочь!
РЕДАКТИРОВАТЬ: компонент формы диагностики выглядит следующим образом:
Diagnose-form.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { PatientCase, Diagnose, CatalogElement} from '../../../models/models';
import { CatalogService } from '../../../services/catalog.service';
import { Observable } from 'rxjs';
import { LoggerService } from '../../../services/logger.service';
@Component({
selector: 'doc-diagnose-form',
templateUrl: './diagnose-form.component.html',
styleUrls: ['./diagnose-form.component.css'],
})
export class DiagnoseFormComponent implements OnInit {
diagnoseForm: FormGroup;
CATALOG = 'icds';
CATALOG_VERSION = 'ICD10-GM-2016';
codeChangeLog: string[] = [];
@Input() pc: PatientCase;
@Input() diagnose: Diagnose;
@Output() onChangeDiagnose = new EventEmitter();
@Output() onDeleteDiagnose = new EventEmitter();
constructor (
private fb: FormBuilder,
private catalogService: CatalogService,
private logger: LoggerService ) {
this.createForm();
this.logCodeChange();
}
ngOnInit() {
this.logger.log('OnInit DiagnoseForm');
this.getCatalogElement(this.diagnose).subscribe(success => {
this.diagnoseForm.setValue({
code: this.diagnose.code,
});
this.diagnose.text = success.text;
this.logger.log('Successfully set initial form values!', success)
}, error => {
this.diagnose.text = 'Ungültige Diagnose!';
this.logger.error('Failed to populate the form!', error);
});
}
createForm(): void {
this.diagnoseForm = this.fb.group({
code: '',
});
}
logCodeChange(): void {
const codeControl = this.diagnoseForm.get('code');
codeControl.valueChanges.forEach(
(value: string) => {
this.codeChangeLog.push(value);
this.logger.log('CodeChangeLog: ', this.codeChangeLog)
}
);
}
isPrimaryDiagnose(): boolean {
return this.pc.all_diagnoses.indexOf(this.diagnose) === 0;
}
/**
* Retrieves the catalog element that corresponds to the diagnose.
*
* @param value the diagnose form value to find catalog element
* @returns {Observable<CatalogElement>} a catalog element as observable
*/
getCatalogElement(value: any): Observable<CatalogElement> {
return new Observable(observer => {
this.catalogService.getSingleElementForTypeByCode(this.CATALOG, this.CATALOG_VERSION, value.code).subscribe(
(catalogElement: CatalogElement) => {
observer.next(catalogElement);
observer.complete();
},
error => {
this.logger.error('An error occurred while getting catalog element!', error);
observer.error(error);
observer.complete();
})
});
};
/**
* Removes the diagnose from the diagnose array of the current patient case.
*/
deleteDiagnose(): void {
this.onDeleteDiagnose.emit({diagnose: this.diagnose, isPrimaryDiagnose: this.isPrimaryDiagnose()});
};
/**
* Saves a new patient case with the updated diagnose array.
*/
saveDiagnose(code: string, text: string): void {
this.onChangeDiagnose.emit({code: code, text: text, oldDiagnose: this.diagnose, isPrimaryDiagnose: this.isPrimaryDiagnose()})
}
/**
* Updates the current diagnose.
*
* @param value The diagnose form that contains the code of the diagnose.
*/
updateDiagnose(value: any): void {
if (value.code !== '' && value.code !== this.diagnose.code) {
this.getCatalogElement(value).subscribe(success => {
this.saveDiagnose(success.code, success.text);
this.logger.log('Successfully updated diagnose!', success);
},
error => {
this.logger.error('An error occurred while update diagnose!', error)
});
}
};
}