【问题标题】:Parent component property doesn´t change in Input() child component in Angular 10Angular 10 中的 Input() 子组件中的父组件属性不会改变
【发布时间】:2021-02-23 16:21:49
【问题描述】:

我想要一个在加载 文档 时在子组件中触发的事件。 当我在父组件中将 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]);
});

}

【问题讨论】:

    标签: javascript angular typescript filereader


    【解决方案1】:

    似乎是一种反模式。为什么不直接在子组件中使用生命周期钩子:ngOnChanges();

    ngOnChanges(){
        if (this.readyToUpload) { // ...code }
    }
    

    https://angular.io/api/core/OnChanges

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 2017-02-15
      • 2020-03-08
      • 2017-05-18
      • 2016-05-21
      • 2020-01-02
      • 2019-11-23
      • 2018-07-02
      相关资源
      最近更新 更多