在 Angular 中从 @Input 更新 ngOnChanges 视图

Update view on ngOnChanges from @Input in Angular

我在 Person 类型的子组件中有一个 @Input 属性,我通过属性从父组件传递对象

完整的工作代码在 StackBlitz

中可用

我探讨了以下问题,我明白了他们在答案中所说的内容,但我根据答案尝试了 Object.assign 和其他操作,但无法在视图中加载数据。

如何通过@Input 传递对象,一旦对象到达子组件并需要在视图中更新,我如何进行一些操作?

示例代码:

应用组件:

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 然后适当的对象没有任何工作。

因为ngOnInitngOnChanges之后的运行。所以你首先设置它,然后立即在你的 ngOnInit.

中重置它

参见here一个工作示例。

基本上将您的组件 person 属性更改为:

person: Person = {
  firstName: '',
  lastName: ''
};

并删除 ngOnInit.

您还可以在个人资料输入中使用 setter,这样您就不需要 ngOnChanges:

@Input('user-profile') set profile(person: Person) {
  this.person.firstName = profile && profile.firstName || '';
  this.person.lastName = profile && profile.lastName || '';
}

person: Person = {
  firstName: '',
  lastName: ''
};

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)
    }
  }

}

https://stackblitz.com/edit/angular-input-ng-onchange-qiyghn?file=src%2Fapp%2Fuser%2Fuser.component.ts