0

我想知道 ngOnChanges 回调是如何工作的。所以我添加了它来观察使用 Input 装饰器注释的属性的变化,如下所示:

@Input() postsToAddToList: Post[] = [];

现在,当我编译代码时,我添加了一些值,这些值会导致使用@Input 注释的属性发生更改,但这不会导致调用和执行 ngOnChanges 回调。请参阅下面发布的屏幕截图中显示的日志。

我想查看浏览器中显示的 ngOnChanges 中的日志。请让我知道是什么阻止了正确调用和调用 ngOnChanges

app.component.ts

import { Component } from '@angular/core';
import { Post } from './post-create/post-create.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'binding2';
  postsArray: Post[] = [];

  onReceiveSubmittedEvtEmitter(post: Post) {
    this.postsArray.push(post);
    console.log("onReceiveSubmittedEvtEmitter->: post.title: " + post.title);
    console.log("onReceiveSubmittedEvtEmitter->: post.content:" + post.content);
  }
}

app.component.html

<app-post-create (onPostSubmittedEvtEmitter)="onReceiveSubmittedEvtEmitter($event)"></app-post-create>
<app-post-list [postsToAddToList]="postsArray"></app-post-list>

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) {
      if (changes.hasOwnProperty(changedProperty)) {
        
        console.log("ngOnChanges->: changedProperty: " + changedProperty);
        console.log("ngOnChanges->: changedProperty:" + changedProperty);

        switch(changedProperty) {
          case 'postsToAddToList':
            console.log("ngOnChanges->: changes[changedProperty].previousValue: " + changes[changedProperty].previousValue);
            console.log("ngOnChanges->: changes[changedProperty].currentValue):" + changes[changedProperty].currentValue);
            break;
        }
      }
    }
  }
}

post-list.component.html

<!-- post-list.component.html -->
<h3>List</h3>

<ng-container *ngIf="postsToAddToList.length; else elseTemplate">

    <ul class="list-group">
        <li class="list-group-item" *ngFor="let post of postsToAddToList; let i = index">
            <h5>{{i+1}}) {{post.title}}</h5>
            <p>
                {{post.content}}
            </p>
        </li>
    </ul>

</ng-container>
<ng-template #elseTemplate>

    <div class="alert alert-danger" role="alert">
        No Post Found!
    </div>

</ng-template>

错误截图

在此处输入图像描述

4

1 回答 1

1

push()您在父组件中使用时,ngOnChanges不会在子组件中调用。每次发生变化时,push()您都可以重新分配值,而不是使用。postsToAddToList

于 2021-04-05T11:34:01.073 回答