我在 Person 类型的子组件中有一个 @Input 属性,我通过属性从父组件传递对象
完整的工作代码在 StackBlitz 中可用。
我探讨了以下问题,我明白了他们在答案中所说的内容,但我根据答案尝试了 Object.assign 和其他东西,但它无法在 View 中加载数据。
如何通过@Input 传递对象,一旦对象到达子组件并需要在 View 中更新,我如何进行一些操作?
示例代码:
应用组件:
import { Component } from '@angular/core';
import { Person } from './models/person'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
person: Person = {
firstName: 'Emma',
lastName: 'Watson'
};
}
应用组件 HTML:
<user [user-profile]="person"></user>
用户组件:
import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Person } from '../models/person';
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit, OnChanges {
@Input('user-profile') profile: Person;
person: Person;
constructor() {}
ngOnInit() {
this.person = {
firstName: '',
lastName: ''
}
}
ngOnChanges(changes:SimpleChanges): void {
if(typeof this.profile !== 'undefined'
&& typeof this.profile.firstName !== 'undefined'
&& typeof this.profile.lastName !== 'undefined') {
this.person.firstName = this.profile.firstName;
this.person.lastName = this.profile.lastName;
}
}
}
用户组件 HTML:
Full Name: {{person.firstName}} {{person.lastName}}
从 @Input
收到对象后,我需要进行一些操作,并且需要在 UI 中更新它。我知道对象作为引用传递,但在这里我尝试使用 Object.assign
并使用 undefined
分配属性,然后适当的对象没有任何工作。
最佳答案
从 ngOnInit()
中删除 person
的分配,ngOnInit 在 ngOnChanges
之后运行,因此您将值恢复为空
export class UserComponent implements OnInit, OnChanges {
@Input('user-profile') profile: Person;
person: Person = { firstName: '', lastName: '' }; // initialize it here
constructor() {}
ngOnInit() {
// this.person = {
// firstName: '',
// lastName: ''
// }
}
ngOnChanges(changes:SimpleChanges): void {
if(typeof this.profile !== 'undefined'
&& typeof this.profile.firstName !== 'undefined'
&& typeof this.profile.lastName !== 'undefined') {
console.log(this.profile)
this.person.firstName = this.profile.firstName;
this.person.lastName = this.profile.lastName;
console.log(this.person)
}
}
}
关于javascript - 从 Angular 中的 @Input 更新 ngOnChanges View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55495333/