Angular 即使在使用 ngOnChanges 时,父组件中的 @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 字符串数组值更改时在指令中检测到此更改。我一直认为 @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 文件中的父接口,我也可以看到数组随时间增加和缩小。

所以,我想我会在我的指令中使用 ngOnChanges 来捕获更改,这里是一些简化的代码:

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

@Input() errors: string[];

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

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

使用此代码,我可以在输入初始化时看到正在输出的更改,但当我稍后在父项中更改值时却看不到。问题是我如何使用 setTimeout 更改我的错误数组?我真的很困惑,为什么我不能通过指令 Input() 捕获更改?如果有人能帮助我理解我做错了什么,我将不胜感激。

此外,如果我的措辞令人困惑或有误,请添加评论,我将 reword/rework 这个问题。

Errors 是一个数组,它是一个对象,即不可变的。对于输入以检测 ngonchanges 的变化,您必须为数组分配一个新的引用。其中一种方法是通过使用扩展运算符创建浅拷贝,无论是从数组中添加还是删除任何值。

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