如何解决在服务内部将组件用作TemplateRef
我正在使用Angular 7和ngrx-bootstrap / modal,并且正在尝试为通用搜索创建模式。我已经有了ng-template,可以让我在模态中显示控件,并且可以通过服务调用它(并且样式有效,最后是重要目的)。这里的问题是,我不想每次都需要显示给模态时都通过ng-template,因为此ng-template始终相同。
我已经读到我能做的最好的事情是创建一个组件而不是模板,这听起来很棒,因为我认为这将允许使用@input和@output进行交互。
¿如何在服务内部导入或创建TemplateRef并使用组件实例?
这是到目前为止的服务代码:
import { Injectable } from '@angular/core';
import { BsModalRef,BsModalService,ModalOptions } from 'ngx-bootstrap/modal';
import { SearchControl } from './rm-search-control.component';
@Injectable({
providedIn: 'root'
})
class SearchService
{
//#region Properties
private _modalConfig : ModalOptions = {
backdrop: true,ignoreBackdropClick: false,animated: true
};
//#endregion
//#region Methods
constructor(private modalService : BsModalService) {
}
openSearch(): void {
let searchTemplateRef = ¿?;
/* How do I use this template here?:
<ng-template #searchTemplate>
<div class="search-container">
<em class="fa fa-search search-icon"></em>
<input type="text" class="search-text" placeholder="SEARCH"/>
</div>
</ng-template>
*/
this.modalService.show(searchTemplateRef,this._modalConfig);
}
//#endregion
//#region Accessors
//#endregion
}
export { SearchService }
解决方法
您可以创建一个组件,该组件将具有搜索和模板的所有逻辑,并且可以从Bootstrap Modal Controller中传递该组件引用而不是模板引用。
this.modalService.show(ModalContentComponent)
不要忘记将新组件作为entryComponent包含在模块内部,因为它将用于将其传递给模态控制器。
这是您可以检查它的官方示例here:
import { Component,OnInit } from '@angular/core';
import { BsModalService,BsModalRef } from 'ngx-bootstrap/modal';
@Injectable({
providedIn: 'root',})
export class DemoModalService {
bsModalRef: BsModalRef;
constructor(private modalService: BsModalService) {}
openModalWithComponent() {
const initialState = {
list: [
'Open a modal with component','Pass your data','Do something else','...'
],title: 'Modal with component'
};
this.bsModalRef = this.modalService.show(ModalContentComponent,{initialState});
this.bsModalRef.content.closeBtnName = 'Close';
}
}
/* This is a component which we pass in modal*/
@Component({
selector: 'modal-content',template: `
<div class="modal-header">
<h4 class="modal-title pull-left">{{title}}</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul *ngIf="list.length">
<li *ngFor="let item of list">{{item}}</li>
</ul>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="bsModalRef.hide()">{{closeBtnName}}</button>
</div>
`
})
export class ModalContentComponent implements OnInit {
title: string;
closeBtnName: string;
list: any[] = [];
constructor(public bsModalRef: BsModalRef) {}
ngOnInit() {
this.list.push('PROFIT!!!');
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。