Angular的@Input()不更新的值即使在使用ngOnChanges时也会在父组件中改变 &g



我有一个小问题,我不知道问题是什么,也许有人在这里可以帮助?

在我的Angular应用中,我有一个组件,它包含一个附加到表单输入的子指令。这个子指令接受一个@Input(),它是一个名为errors的字符串数组。

在父HTML模板中我们有这样的内容。

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

我想让它,当errorssting数组值改变这种变化是在指令检测。我一直认为@Inputs()被视为可观察对象,因此在父组件中我做了以下操作(为了简单起见,我减少了代码)

@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()捕获变化?如果有人能帮助我了解我做错了什么,我将非常感激。

如果我的措辞令人困惑或错误,请添加评论,我将重写/重新编写这个问题。

Errors是一个数组,它是一个对象,即不可变。为了检测ngonchanges中的变化,你必须给数组分配一个新的引用。其中一种方法是通过在数组中添加或删除任何值时使用扩展操作符来创建浅复制。

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

最新更新