我正在创建一个组件,我将有3个按钮[ Edit, Cancel, Save ]
,当用户单击编辑按钮时,将出现“保存并取消”按钮,当单击“保存”按钮时,它将触发一个功能父组件。
问题是当我将一个函数从父组件传递给ESC组件时,它无法从父组指令访问其他函数。
注意该组件将用作不同的全局操作 部件
Plunker:http://plnkr.co/edit/ZmyFjwhM6tPZXubTfeGA?p=preview&open=app%2Fapp.component.ts
代码:
<div [hidden]="isEdit">
<button (click)="toggleEdit()">Edit</button>
</div>
<div [hidden]="!isEdit">
<button (click)="runFunction(); toggleEdit()">Save</button>
<button (click)="toggleEdit()">Cancel</button>
</div>
export class EscComponent {
@Input() run: Function;
runFunction() {
console.log('Run Function')
this.run()
}
isEdit = false;
toggleEdit() {
this.isEdit = !this.isEdit;
}
}
父组件:
Component usage: <app-esc [run]="setName"></app-esc>
export class AppComponent {
name = 'Angular';
setName() {
this.setNameCd();
}
setNameCb() {
this.name = 'Angular 2 asd';
}
}
答案 0 :(得分:0)
@Harry Ninh is right, you should use the decorator @Output
or create a specific service. Here is a working Plunker with @output:
http://plnkr.co/edit/wadCAyW5kah0VjVR2m5B?open=app%2Fapp.component.ts&p=preview
You have also a few typo in your original plunker, so you should review your code for others typos.
Here is how it works:
Parent listen to the output
<app-esc (endEditing)="setName($event)"></app-esc>
In child component, import @Output and EventEmitter
import { Component, Input, Output, EventEmitter } from '@angular/core';
Initiate the output:
@Output() endEditing = new EventEmitter();
Emit the event in relevant function
this.endEditing.emit();