angular - 如何在服务中加载组件(Angular 2+)?
问题描述
我想ng-template
在服务中加载一个,以创建一个对话框。
有没有办法做到这一点?
例子:
@Component({
selector: "temp",
template: ` <ng-template #dialogTemplate>
<p>{{ line1 }}</p>
<p>{{ line2 }}</p>
</ng-template>`,
})
class DialogTemplateComponent {
@ViewChild("dialogTemplate")
public teplateRef: TemplateRef<any>;
constructor() {}
public line1: string = "test";
public line2: string = "test2";
}
@Injectable({ providedIn: "root" })
export class ActionDialogBoxService {
/// let templateRef = DialogTemplateComponent.templateRef
/// render the templateRef in a dialogbox
}
解决方案
您只需将该模板作为函数参数传递给服务。完全相同的事情是在MatDialog
@ViewChild("dialogTemplate")
public teplateRef: TemplateRef<any>;
private dialoService:ActionDialogBoxService;
dialogService.openDiaog(this.templateRef,....);
您可以将其用作实现参考https://material.angular.io/components/dialog/overview