【发布时间】:2017-06-17 09:10:41
【问题描述】:
我想知道执行此操作的最佳方法,以及是否有不同的方法。我正在尝试从其父组件调用子组件中的函数。所以如果我有:
<parent>
<child></child>
</parent>
...而child 具有称为show() 或hide() 的函数,我如何从parent 调用其中任何一个?
【问题讨论】:
标签: angular typescript
我想知道执行此操作的最佳方法,以及是否有不同的方法。我正在尝试从其父组件调用子组件中的函数。所以如果我有:
<parent>
<child></child>
</parent>
...而child 具有称为show() 或hide() 的函数,我如何从parent 调用其中任何一个?
【问题讨论】:
标签: angular typescript
在模板内部,使用模板变量/引用:
<parent (click)="yourChild.hide()">
<child #yourChild></child>
</parent>
现场演示:https://stackblitz.com/edit/angular-so-3?file=src%2Fapp%2Fapp.component.html
或
组件内部:
import { ..., ViewChild, ... } from '@angular/core';
// ...
export class ParentComponent {
@ViewChild('yourChild' /* #name or Type*/, {static: false}) 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 /* #name or Type*/, {static: false}) 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
【讨论】:
ViewChildren 用于多个孩子!使用名称或类的方式相同。
ViewChild 会拿起第一个找到的! ;)
要调用子函数,您需要@ViewChild。但是,对于显示/隐藏组件,您最好在模板中解决这个问题:
<parent>
<button (click)="showChild=!showChild">Toggle child</button>
<child *ngIf="showChild"></child>
</parent>
无需声明自定义函数hide()。
【讨论】:
嗯,其他答案是正确的,但我认为有时该函数应该以从父到子的角度方式的数据流调用,所以你真正需要的是每次运行一个函数父组件中的变量已更改。见下文:
@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");
}
}
【讨论】: