2017-08-08 54 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

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