我想知道最好的方法,如果有不同的方法。我试图从其父组件中调用子组件中的函数。如果我有:
<parent>
<child></child>
</parent>
... child
有show()
或hide()
的功能,如何调用parent
中的任何一个?
答案 0 :(得分:69)
模板内部:
<parent (click)="yourChild.hide()">
<child #yourChild></child>
</parent>
组件内部(选项1):
import { ..., ViewChild, ... } from '@angular/core';
// ...
export class ParentComponent {
@ViewChild('yourChild') child;
ngAfterViewInit() {
console.log('only after THIS EVENT "child" is usable!!');
this.child.hide();
}
}
组件内部(选项2):
import { ..., ViewChild, ... } from '@angular/core';
import { ..., ChildComponent, ... } from '....';
// ...
export class ParentComponent {
@ViewChild(ChildComponent) child;
ngAfterViewInit() {
console.log('only after THIS EVENT "child" is usable!!');
this.child.hide();
}
}
请参阅官方文档:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child
live demo plunker:https://plnkr.co/edit/fEYwlKlkMbPdfx9IGXGR?p=preview
答案 1 :(得分:4)
其他答案都是正确的,但是我认为有时候应该以从父到子的角度方式用数据流调用该函数,因此,您真正需要的是每次父组件中的变量已更改。见下文:
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
variable = "yes!";
toggle() {
this.variable = this.variable === "yes!" ? "hell no!" : "yes!";
}
}
应用模板:
<button (click)="toggle()">Toggle</button>
Parent says: {{variable}}
<p>
<app-child [childVar]="variable"></app-child>
</p>
子组件:
export class ChildComponent implements OnInit {
_childVar: string; // if you need to record the value and access later in child component
counter = 0;
@Input()
set childVar(value: string) {
this._childVar = value;
this.childFunction(); // the answer is here
}
childFunction() {
this.counter++;
console.log("called child function");
}
}
测试
答案 2 :(得分:3)
要调用孩子的某个功能,您需要@ViewChild
。但是,为了显示/隐藏组件,最好在模板中解决此问题:
<parent>
<button (click)="showChild=!showChild">Toggle child</button>
<child *ngIf="showChild"></child>
</parent>
无需声明自定义函数hide()
。