Angular 4 @Input 属性更新不影响 UI

2024-03-07

有 2 个组件:parentComponent 和 ChildComponent,它们在父级内部定义。 在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 初始化为新的 Person 时,UI 才会“捕获”更改?


请注意子组件的变化

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...

 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 4 @Input 属性更新不影响 UI 的相关文章

随机推荐