#javascript #angular #typescript #filereader
#javascript #angular #typescript #filereader
Вопрос:
Я хочу событие, которое срабатывает в дочернем компоненте при загрузке документов. Когда я устанавливаю для readyToUpload значение TRUE в родительском компоненте (в функции с жирной стрелкой), дочерний компонент не обнаруживает изменения в свойстве Input()… Почему это происходит? Причина функций жирной стрелки?
child.component.ts
@Input() public readytoUpload: boolean;
async save() {
this.getFormValidationErrors();
this.submitted.emit();
if (this.errors.length > 0) return;
if (this.frm){
var check = async (ready: boolean) => {
if (ready) {
return;
}
setTimeout(check, 2000);
}
await check(this.readytoUpload);
}
parent.component.html
<app-child (submitted)="onSubmit();" [readyToUpload]="readyToUpload">
parent.component.ts
inputs_to_docs(input_array: Array<any>) {
this.documents = [];
var document_count = 0;
input_array.forEach(element => {
let doc = {};
doc.contentType = element.files[0].type;
doc.fileName = element.files[0].name;
doc.fileSize = element.files[0].size;
let reader = new FileReader();
reader.onload = () => {
doc.fileAsBase64 = reader.result.toString();
let docs_aux: Array<any> = this.documents.slice();
docs_aux.push(doc);
this.documents = docs_aux;
document_count;
if (document_count == input_array.length) {
this.readyToUpload = true;
}
}
reader.readAsDataURL(element.files[0]);
});
}
Ответ №1:
Похоже на анти-шаблон. Почему бы вам просто не использовать lifecycle-hook: ngOnChanges();
в дочернем компоненте
ngOnChanges(){
if (this.readyToUpload) { // ...code }
}