[英]How to access a service inside TemplateRef which was provided in parent component?
[英]Use component as a TemplateRef inside a Service
我正在使用 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 模态控制器中,您可以传递该组件引用而不是模板引用。
this.modalService.show(ModalContentComponent)
不要忘记将新组件作为 entryComponent 包含在您的模块中,因为它将用于将其传递给模态控制器。
这是官方示例,您可以在此处查看:
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!!!');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.