簡體   English   中英

如何從另一個組件調用一個組件中的方法是 angular2

[英]how to call a method in one component from another component is angular2

這里方法 load() 在app.component.ts定義, <app-child></app-child>app.component.html傳遞, 'load('1', 'value', msc)'方法是從child.component.html

如何調用load()方法?

app.component.ts
    -----------------
    load(id, value, msc){
    alert(id)
    }
    app.component.html
    ----------------------
    <app-child></app-child>

    child.component.html
    ---------------------
    <div (click)= 'load('1', 'value', msc)'>btn1</div>

您可以使用共享服務並使公共功能在兩個組件中都可用

您可以為此使用事件綁定:

// parent template
<app-child (onLoad)="load(...$event)></app-child>

// child template
<div (click)='onLoad.emit(['1', 'value', msc])'>btn1</div>    

// child controller
@Output() onLoad = new EventEmitter<any>();

https://angular.io/guide/template-syntax#custom-events-with-eventemitter

您可以使用 @Output 並發出一個包含三個參數的對象:

 // app.component.ts: load(id, value, msc){ alert(id) } loadEv = ($event) => { this.load($event.param1, $event.param2, $event.param3); } // app.component.html: <app-child (loadEvent) = loadEv($event)></app-child> // child.component.html: <div (click)= 'load('1', 'value', msc)'>btn1</div> // child.component.ts: import { Output, EventEmitter } from '@angular/core'; @Output() loadEvent = new EventEmitter<any>(); load(param1, param2, param3): any { this.loadEvent.emit({param1, param2, param3}); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM