Trying to grasp the concept of the ngOnChanges() callback, I created an example below. Despite having values for the attributes title and content in the Post interface during compile time, I do not see any logs from ngOnChanges.
Please advise on the correct usage.
app.component.ts:
import { Component, OnInit, OnChanges, SimpleChanges, Output, EventEmitter } from '@angular/core';
export interface Post {
title: string;
content: string;
}
@Component({
selector: 'app-post-create',
templateUrl: './post-create.component.html',
styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent implements OnInit {
@Output() post: Post;
@Output() onPostSubmittedEvtEmitter: EventEmitter<Post> = new EventEmitter<Post>();
constructor() {
this.post = {} as Post;
}
ngOnInit(): void {}
ngOnChanges(changes: SimpleChanges) {
for (let changedProperty in changes) {
console.log("ngOnChanges-> previousValue: " + changes[changedProperty].previousValue);
console.log("ngOnChanges-> currentValue: " + changes[changedProperty].currentValue);
}
}
onSubmitPost(post: Post) {
this.post = {
title: this.post.title,
content: this.post.content
};
this.onPostSubmittedEvtEmitter.emit(this.post);
console.log("onSubmitPost-> post.title: " + post.title);
console.log("onSubmitPost-> post.content: " + post.content);
}
}
update 05.04.2021
I have now added ngOnChanges to monitor changes in a property annotated with the Input decorator:
@Input() postsToAddToList: Post[] = [];
Upon compiling the code and adding values, I receive the following logs from ngOnChanges:
ngOnChanges-> previousValue: undefined
ngOnChanges-> currentValue:
However, the issue arises when adding more values as I do not see any logs from ngOnChanges despite changing the contents of the object decorated with @Input. Can anyone explain why?
post-list.component.ts:
import { Component, Input,OnInit, OnChanges, SimpleChanges, Output, EventEmitter } from '@angular/core';
import { Post } from '../post-create/post-create.component';
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {
constructor() {}
@Input() postsToAddToList: Post[] = [];
ngOnInit(): void {}
ngOnChanges(changes: SimpleChanges) {
for (let changedProperty in changes) {
console.log("ngOnChanges-> previousValue: " + changes[changedProperty].previousValue);
console.log("ngOnChanges-> currentValue: " + changes[changedProperty].currentValue);
}
}
}