我想通過調用子組件 的函數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?
退房https://angular.io/tutorial的參考來獲得如何角作品的一個基本的瞭解:) – j2L4e
的[角2調用一個可能的複製子組件方法從父](https://stackoverflow.com/questions/45078725/angular-2-calling-a-child-component-method-from-the-parent) – echonax
您可以訪問子組件使用Viewchild 。 https://angular.io/guide/component-interaction –