Reputation: 3209
I use Angular 9 and modify a variable that I use in a template. But unfortunately my template does not get updated. Can anyone explain me what the typical approach is to let Angular know that something in my component changed?
projects: any[] = [];
ngAfterViewInit(): void {
this.actRoute.params.subscribe((params) => {
this.electronService.foo.bar(
.then((x) => {
var history = x.y();
history.on("begin", () => {
this.projects.push('foo');
});
history.execute();
});
});
}
foo.component.html
<ul>
<li *ngFor="let project of projects;">{{project}}</li>
</ul>
Upvotes: 2
Views: 3852
Reputation: 65
You must assign the new value to the variable you want to see changed (project
) otherwise Angular will not notice the change because the value of your variable is of type object.
The answer is this:
this.projects = this.projects.concat(['foo'])
Instead of: this.projects.push('foo')
(which is "wrong" in Angular)
Upvotes: 1
Reputation: 2514
Angular will not detect the changes if you don't change the "in memory" variable. In your case, just pushing the same variable will not trigget the change detection. You should this.projects = this.projects.slice()
or something like that to change the memory variable and trigger the change. If that doesn't fit you, there are other things you can use like Injecting ChangeDetector
then calling ChangeDetector.detectChanges();
constructor(private cd: ChangeDetectorRef) {}
...
this.projects.push('foo');
this.cd.detectChanges();
...
Upvotes: 0
Reputation: 12900
You need to use the arrow function. this
doesn't have the same meaning as you think it does
ngAfterViewInit(): void {
let projects = this.projects;
projects = [];
this.actRoute.params.subscribe((params) => {
this.electronService.foo.bar(
.then((x) => { // arrow function
const history = x.y(); // use const
history.on("begin", () => { // arrow function
projects.push('foo');
});
history.execute();
});
});
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Upvotes: 1