本文介绍了Angular 2+:父值更改时更新@Input属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父级和子级组件,其中父级通过@Input装饰器将对象传递给子级.问题是子级仅获取一次父级数据,然后在将来更改传递给子级的父级属性后,该值就不会更新.

I have a parent and child component where the parent is passing an object to the child through the @Input decorator. The problem is the child gets the parent data only once, then after future changes to parent property that is passed to the child, the value is not being update.

推荐答案

在更改父组件时,也要在子组件中进行更改

这是您可以使用OnChanges界面执行的操作,该界面可以检测组件中的更改

Here is how you can do with OnChanges interface which detects changes in the component

parent.component.html

In parent.component.html

<app-child [child_name]="name"></app-child>

child.component

In child.component

export class ChildComponent implements OnChanges {

  @Input('child_name') name: string
  text: string
  constructor() { }

  // on every change of @input 'name', this method will be triggered
  ngOnChanges() {
    this.text = 'Hi ' + this.name
  }

}

这篇关于Angular 2+:父值更改时更新@Input属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:14