【问题标题】:Angular 4 @Input property update does not affect the UIAngular 4 @Input 属性更新不影响 UI
【发布时间】:2017-10-07 08:01:05
【问题描述】:

有 2 个组件:parentComponent 和 ChildComponent,它们在 parent 内部定义。 在 parentComponent 中有一个局部变量,用作传递给 ChildComponent 的输入属性的值(使用 getter)。

父组件.ts:

@Component({
selector:'parent-component',
template:`
<h1>parent component</h1>
<child-component [personData]="PersonData"></child-component>
`
})
export class ParentComponent{
personData:Person;

get PersonData():Person{
return this.personData;
}

set PersonData(person:Person){
this.personData = person;
}

ngOnInit(){
this.PersonData = new Person();
this.PersonData.firstName = "David";
}

//more code here...

}

子组件.ts:

@Component({
    selector:'child-component',
    template:`
    <h1>child component</h1>
    <div *ngIf="personData">{{personData.firstName}}</div>
    `
    })
export class ChildComponent{
    @Input() personData:Person;        

    //more code here...

 }

问题是:在父组件的某个地方,当特定事件发生时,函数newPersonArrived(newPerson:PersonData)被调用,函数代码如下:

newPersonArrived(newPerson:Person){
    this.PersonData = newPerson;
    }

这不会影响带有新人名的 UI!

只有以下有帮助:

newPersonArrived(newPerson:Person){
    this.PersonData = new Person();
    this.PersonData.firstName = newPerson.firstName;
    }

这是预期的行为吗?

为什么只有当 personData 初始化为 new Person 时,UI 才会“捕捉”变化?

【问题讨论】:

  • 你在哪里打电话给newPersonArrived?它应该工作
  • 在父组件中发生一些事件后,我看到函数被调用(我放在那里 console.log('aa') 并看到它被打印出来了)
  • 我看到了这个例子,所以你的意思是这取决于我要参加哪个活动?听起来很有趣
  • 我不太清楚。为了更好地理解它,我们需要一些工作示例

标签: javascript angular ngonchanges


【解决方案1】:

请注意子组件的变化

import { Component, Input, Output, OnChanges, EventEmitter, SimpleChanges } from '@angular/core';

@Component({
    selector:'child-component',
    template:`
    <h1>child component</h1>
    <div *ngIf="personData">{{personData.firstName}}</div>
    `
    })
export class ChildComponent implements OnChanges{
    @Input() personData:Person; 
     public ngOnChanges(changes: SimpleChanges) {
          if ('personData' in changes) {
              //some code here
           }
      }       

    //more code here...

 }

【讨论】:

  • 我试过这个,但我尝试的第一种方式没有调用 ngOnChanges (this.PersonData = newPerson),只有当我执行 new Person() 时,但在这种情况下,UI已更新,我不需要 ngOnChanges....
  • 这对我有用。如果父数据快速变化,我无法将最新数据“推送”给孩子。 OnChanges 奏效了。谢谢。
  • 像魅力一样为我工作
猜你喜欢
  • 1970-01-01
  • 2020-11-04
  • 2010-12-24
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
相关资源
最近更新 更多