【问题标题】:Child component property doesn't change子组件属性不变
【发布时间】:2016-09-07 02:58:00
【问题描述】:

这可能是一个简单的错误,但我自己无法弄清楚。

假设我们有一个父组件,里面有一个子组件。该子组件具有下一个属性:

private n : Number = 0;

还有一个方法:

plusOne(){
    this.n += 1;
}

所以,每次我们调用“plusOne”方法时,“n”属性都会将它的值增加 1。 如果我从子组件内部调用此方法,一切正常。 问题是当从父组件调用方法时(使用 ViewChild),属性不会改变值。实际上,使用console.log我已经检查了方法被成功调用并且属性在方法的生命周期中改变了值。

在后来的故障排除中,我将属性更改为

public n : Number = 0;

然后尝试从父组件直接访问它

this.child.n = 1;

但属性仍然没有改变。

【问题讨论】:

  • 这在我看来不像是 JavaScript...

标签: angular


【解决方案1】:

你可以试试下面,

阅读更多关于parent - child interaction using ViewChild here

import { Component, OnDestroy, OnInit } from '@angular/core';
import { AfterViewInit, ViewChild } from '@angular/core';

@Component({
  selector: 'child-component',
  template: '<p>{{num}}</p>'
})
export class ChildComponent implements OnInit, OnDestroy {
  num = 0;
}

@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1>
  <button (click)="updateChild()" >Update child NUM</button>
  <child-component></child-component>
  `
})
export class AppComponent {
   @ViewChild(ChildComponent)
   private childComponent: ChildComponent;

  updateChild(){
    this.childComponent.num +=1;
  }
}

这里是Plunker!!

希望这会有所帮助!

【讨论】:

  • 谢谢!我解决问题。我将样式分配给模板错误。在和你的笨蛋玩了一点之后,我意识到这一点!谢谢
  • 很高兴它有帮助..干杯!!
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2018-12-15
  • 2017-05-11
  • 2021-06-27
相关资源
最近更新 更多