У меня есть два компонента: NgbdAlertCloseable и AlertCtrl. Также у меня есть компонент AppComponent как родительский компонент. Я хочу щелкнуть кнопку в компоненте AlertCtrl и создать предупреждение на компоненте NgdbAlertCloseable.Функция вызова Angular2 от другого компонента
Функция addSuccess() добавляет предупреждение в представление и хорошо работает, когда я вызываю его внутри своего компонента. Тем не менее, я пытался использовать EventEmitter, чтобы вызвать эту функцию из другого компонента (как предложено здесь: https://stackoverflow.com/a/37587862/5291422), но он дает эту ошибку:
ORIGINAL EXCEPTION: TypeError: self._NgbdAlertCloseable_2_4.addSuccess is not a function
Вот мои файлы:
ngbd-уведомление-закрывающиеся .component.ts
import { Input, Component } from '@angular/core';
@Component({
selector: 'ngbd-alert-closeable',
templateUrl: './app/alert-closeable.html'
})
export class NgbdAlertCloseable {
@Input()
public alerts: Array<IAlert> = [];
private backup: Array<IAlert>;
private index: number;
constructor() {
this.index = 1;
}
public closeAlert(alert: IAlert) {
const index: number = this.alerts.indexOf(alert);
this.alerts.splice(index, 1);
}
public static addSuccess(alert: IAlert) {
this.alerts.push({
id: this.index,
type: 'success',
message: 'This is an success alert',
});
this.index += 1;
}
public addInfo(alert: IAlert) {
this.alerts.push({
id: this.index,
type: 'info',
message: 'This is an info alert',
});
this.index += 1;
}
}
interface IAlert {
id: number;
type: string;
message: string;
}
бдительные-ctrl.component.ts
import { EventEmitter, Output, Component } from '@angular/core';
import { NgbdAlertCloseable } from './ngbd-alert-closeable.component';
@Component({
selector: 'alert-ctrl',
template: '<button class="btn btn-success" (click)="addSuccessMsg()">Add</button>'
})
export class AlertCtrl {
@Output() msgEvent = new EventEmitter();
public addSuccessMsg(){
this.msgEvent.emit(null);
}
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<div class="col-sm-4"><alert-ctrl (msgEvent)="ngbdalertcloseable.addSuccess()"></alert-ctrl><ngbd-alert-closeable #ngbdalertcloseable></ngbd-alert-closeable>'
})
export class AppComponent { }
Могу ли я использовать его неправильно? Как я могу это исправить?