2017-08-08 31 views
0

我想通過調用子組件 的函數change()來更新我在父組件視圖中使用的str的值,這裏是我的代碼。Angular 2/4:無法更新子組件視圖

import { Component } from '@angular/core'; 
import { ChildComponent } from './child/child.component'; 

@Component({ 
    selector: 'app-root', 
    template: ` 
    <h1>parent</h1> 
    <button (click)="changeChild()">change child</button> 
    <app-child></app-child> 
    `, 
styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    constructor(private cc:ChildComponent) {} 

    changeChild(){ 
     this.cc.change(); 
    } 

} 

和子組件是:

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

@Component({ 
    selector: 'app-child', 
    template: ` 
     <p>{{str}}</p> 
    `, 
    styleUrls: ['./child.component.css'] 
}) 
export class ChildComponent implements OnInit { 

    private str; 

    constructor() { 
     this.str = 'initial' 
    } 

    change(){ 
     this.str = 'changed' 
    } 

    ngOnInit() { 
    } 

} 

但鑑於從未更新值STR爲 「改變」。

請任何幫助,因爲我是新的角4?

+0

退房https://angular.io/tutorial的參考來獲得如何角作品的一個基本的瞭解:) – j2L4e

+1

的[角2調用一個可能的複製子組件方法從父](https://stackoverflow.com/questions/45078725/angular-2-calling-a-child-component-method-from-the-parent) – echonax

+0

您可以訪問子組件使用Viewchild 。 https://angular.io/guide/component-interaction –

回答

-1

使用@ViewChild獲得子組件

in Parent component 


     import {ChildComponent} from 'child.component.ts' 

export class ParentComponent{ 
------ 

@ViewChild(ChildComponent) 
private child:ChildComponent 

--- 

changeChild(){ 
this.child.change() 
} 
} 
+1

這個問題顯然是重複的,不要創建一個回答... –

+0

非常感謝,它的工作原理 –