繁体   English   中英

从 Angular 中的父 component.ts 调用 function

[英]Hot to call a function inside a child component.ts from a parent component.ts in Angular

app.component.html我打印section.component.html的列表

  <div class="col-md-12 col-lg-4" *ngFor="let section of sectionObjectList">
    <app-section [section]="section"></app-section>
  </div>

渲染模板时,我想从app.component.ts (父级)调用列表(子级)的第一个section.component.ts内的 function 。

正确的方法是什么? 谢谢

您可以使用@Output装饰器:

父组件:

HTML:

 <div class="col-md-12 col-lg-4" *ngFor="let section of sectionObjectList">
    <app-section [section]="section" (callback)="childCallback($event)"></app-section>
  </div>

TS:

childCallback(event) {
 console.log("Event data: ",event);
}

子组件:

@Output() callback = new EventEmitter<string>();

someFuntion() {
  callback.emit(value);
}

在子指令和父指令和组件之间共享数据

使用ViewChild进行 DOM 操作(更改本机 HTML 元素),并使用input/output进行数据绑定和控制来自父组件的子组件的 state,以使其保持隔离和无状态。

在 app.component.html 中:

<div class="col-md-12 col-lg-4" *ngFor="let section of sectionObjectList">
    <app-section #section [section]="section"></app-section>
  </div>

在 app.component.ts 中:

export class AppComonent {
 @ViewChild('section) sectionCmp: SectionComponent;

 someMethod() {
    if (this.sectionCmp) {
       this.sectionCmp.childMethod();
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM