【发布时间】:2021-04-19 13:24:48
【问题描述】:
我有一个动态创建的 modalComponent。
<div class="modal">
<div class="modal-body">
Test
</div>
<div class="modal-footer">
<button (click)="callbackFunction()">success</button>
<button>abort</button>
</div>
</div>
这个组件有一个 Input callbackFunction,这是一个我想从我的父组件调用的函数。
import {
Component,
Input,
OnInit,
QueryList,
ViewChildren
} from "@angular/core";
import { ModalService } from "../modal.service";
@Component({
selector: "app-modal",
templateUrl: "./modal.component.html",
styleUrls: ["./modal.component.css"]
})
export class ModalComponent implements OnInit {
@Input() callbackFunction: () => void;
constructor(private modalService: ModalService) {}
ngOnInit() {}
}
之后我创建了一个服务:
import {
ApplicationRef,
ComponentFactoryResolver,
ComponentRef,
Injectable,
Injector
} from "@angular/core";
import { ModalComponent } from "./modal/modal.component";
@Injectable()
export class ModalService {
dialogComponentRef: ComponentRef<ModalComponent>;
open(callbackFunction: any) {
const modalComponentFactory = this.cfResolver.resolveComponentFactory(ModalComponent);
const modalComponent = modalComponentFactory.create(this.injector);
modalComponent.instance.callbackFunction = callbackFunction;
this.dialogComponentRef = modalComponent;
document.body.appendChild(modalComponent.location.nativeElement);
this.appRef.attachView(modalComponent.hostView);
}
close() {
this.appRef.detachView(this.dialogComponentRef.hostView);
}
constructor(
private appRef: ApplicationRef,
private cfResolver: ComponentFactoryResolver,
private injector: Injector
) {}
}
在 componentFactoryResolver 之后,我将函数作为实例传递。
在我的父控制器中,我创建了一个函数
sayHello(
this.myService.doSomething();
}
然后我创建一个用于打开模式的函数
open(this.sayHello());
当我单击按钮并调用回调函数时,“this”不是指父组件而是指模态组件,并且 sayHello 是未定义的。我该如何解决这种情况?
我不想使用 emit。
这是我的堆栈闪电战:Example
【问题讨论】:
-
"我不想使用 emit。"但这将轻松顺利地解决整个情况。这是 EventEmitters 存在的一个完美例子。
标签: javascript angular typescript