我试图理解回调 ngOnChanges() 所以我创建了下面发布的示例。但是在编译时,尽管 Post 接口分别具有其属性 title 和 content 的值,但是,我没有收到来自 ngOnChanges 的任何日志
请让我知道如何正确使用
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->: changes[changedProperty].previousValue: " + changes[changedProperty].previousValue);
console.log("ngOnChanges->: changes[changedProperty].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);
}
}
更新 05.04.2021
按照建议,我添加了 ngOnChanges 来观察使用 Input 装饰器注释的属性的变化,如下所示:
@Input() postsToAddToList: Post[] = [];
现在,当我编译代码时,我添加了一些值,我从 ngOnChanges 收到以下日志:
ngOnChanges->: changes[changedProperty].previousValue: undefined
post-list.component.ts:20 ngOnChanges->: changes[changedProperty].currentValue):
但问题是当我不断添加更多值时,我没有收到来自 ngOnChanges 的任何日志,请告诉我为什么尽管我不断添加更多值导致更改用 @Input 装饰的对象的内容??!
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->: changes[changedProperty].previousValue: " + changes[changedProperty].previousValue);
console.log("ngOnChanges->: changes[changedProperty].currentValue):" + changes[changedProperty].currentValue);
}
}
}