2016-09-07 91 views
0

這可能是一個簡單的錯誤,但我不能自己弄清楚。子組件屬性不變

比方說,我們有一個父組件,裏面有一個子組件。此子組件有一個屬性:

private n : Number = 0; 

和方法:

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

所以,每次我們稱之爲「Plusone精選」方法「N」屬性增加它由1 如果值我從子組件內部調用此方法一切正常。 問題是,當從父組件調用方法(使用ViewChild)時,該屬性不會更改該值。其實,使用console.log我已經檢查過該方法被成功調用,並且該屬性在該方法的生命週期中更改了值。

在故障排除後我改變了屬性

public n : Number = 0; 

然後試圖直接訪問它從父組件

this.child.n = 1; 

但是屬性依然不改。

+0

這看起來不像我的JavaScript ... –

回答

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

希望這有助於!

+0

謝謝!我解決了這個問題。我錯誤地將樣式分配給模板。我意識到,在和你的朋友玩一點點後!謝謝 – Kiddo

+0

很高興幫助..乾杯! –

+0

你可以接受答案。 –