簡體   English   中英

即使使用 ngOnChanges,Angular @Input() 也不會更新父組件中的值

[英]Angular @Input() not updating value is changed in parent component even when using ngOnChanges

我有一個小問題,我不確定是什么問題,也許這里有人可以提供幫助?

在我的 Angular 應用程序中,我有一個包含附加到表單輸入的子指令的組件。 這個子指令采用一個@Input() ,它是一個名為errors的字符串數組。

所以在父 HTML 模板中,我們有類似的東西......

<!-- parent-component.component.html file -->
<input type="text" myDirectiveName [errors]="errors">

我想要它,以便當errors sting 數組值更改時,在指令中檢測到此更改。 我一直認為@Inputs()被視為 Observables 所以在父組件中我做了以下(為了簡單起見,我減少了代碼)

@Component({
  selector: 'parent-component',
  templateUrl: './parent-component.component.html',
  styleUrls: ['./parent-component.component.scss']
})
export class ParentComponent implements OnInit {
    
    // declare the errors string array
    errors = [];

    ngOnInit(): void {
        this.getErrors();
    }

    getErrors(): void {
        setInterval(() => {
          if(this.errors.length > 3) {
            this.errors.length = 0;
          } else {
            this.errors.push('This is an error');
          }
        }, 1000);
    }
}

我認為這會在我的@Input自動更新,但它不會,即使我使用{{ errors | json }}將錯誤數組寫入parent-component.component.html文件中的parent-component.component.html接口 {{ errors | json }}我可以看到數組隨着時間的推移而增加和縮小。

所以,我想我會在我的指令中使用ngOnChanges來捕獲更改,這里是一些簡化的代碼:

@Directive({
  selector: '[myDirectiveName]'
})
export class errorDirective implements OnInit, OnChanges {

@Input() errors: string[];

ngOnInit() {
// do stuff...
}

ngOnChanges(simpleChange: any) {
    console.log(simpleChange);
  }
}

使用此代碼,我可以看到在 Input 初始化時輸出的更改,但當我稍后在父級中更改值時則看不到。 問題是我如何使用setTimeout更改我的錯誤數組? 我真的很困惑為什么我不能通過 Directive Input()捕獲更改? 如果有人能幫助我理解我做錯了什么,我將不勝感激。

此外,如果我的措辭令人困惑或錯誤,請添加評論,我將改寫/重新處理這個問題。

Errors 是一個數組,它是一個對象,即不可變的。 對於檢測ngonchanges變化的輸入,你必須為數組分配一個新的引用。 一種方法是通過使用擴展運算符創建淺拷貝,在任何地方添加或刪除數組中的任何值。

this.errors.push('new error');
this.errors = [...this.errors];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM