我想通过调用子组件的函数change()来更新我在父组件的子组件视图中使用的str的值 这是我的代码。
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从未更新为&#34;已更改&#34;。
请帮助,因为我是Angular 4的新手?
答案 0 :(得分:-1)
使用@ViewChild获取子组件的引用
in Parent component
import {ChildComponent} from 'child.component.ts'
export class ParentComponent{
------
@ViewChild(ChildComponent)
private child:ChildComponent
---
changeChild(){
this.child.change()
}
}