我正试图建立一个页面,有两个JSON代码编辑器并排放置,可以显示两个不同的JSON代码片段,也可以不同的配置,如果需要(即分开的主题,设置,大小和错误)使用ACE编辑器.
到目前为止,我已经算出了大部分工作.然而,我正在try 将相同的代码编辑器共享组件重用为单一父组件中的两个子实例,我希望将这两个实例显示为两个编辑器,显示不同的JSON值和其他参数,这对我来说是行不通的.
以下是代码:
parent.component.html个
<div class="projects">
<!-- layer to display two editors side by side -->
<div class="row no-margin">
<div class="col">
child editor 1
<childComponent [template]="childTemplate1" jsonValue="{name:joe}" #childEditor1></childComponent>
</div>
<div class="col">
child editor 2
<childComponent [template]="childTemplate2" jsonValue="{name:bob}" #childEditor2></childComponent>
</div>
</div>
</div>
<ng-template #childTemplate1>
<div class="app-ace-editor" #childEditor1 style="height: 80vh;"></div>
</ng-template>
<ng-template #childTemplate2>
<div class="app-ace-editor" #childEditor2 style="height: 80vh;"></div>
</ng-template>
parent.component.ts个
@ViewChild('childEditor1') private childEditor1: ElementRef<HTMLElement>;
@ViewChild('childEditor2') private childEditor2: ElementRef<HTMLElement>;
@ViewChild(SharedCodeEditorChildComponent) private childEditor: SharedCodeEditorChild;
constructor() { }
ngOnInit(): void {
}
/* invoke ace editor's method based on the child editor instances */
ngAfterViewInit(): void {
this.childEditor.invokeEditor(this.childEditor1);
this.childEditor.invokeEditor(this.childEditor2);
}
sharedCodeEditorChild.component.html
<ng-container *ngTemplateOutlet="template"></ng-container>
sharedCodeEditorChild.component.ts个
@Input() template: TemplateRef<any>;
constructor() { }
ngAfterContentInit(): void {
}
ngOnInit(): void {
}
ngAfterViewInit(): void {
}
invokeEditor(elem:any) {
ace.config.set("fontSize", this.fontSize + 'px');
ace.config.set('basePath', 'https://unpkg.com/ace-builds@1.4.12/src-noconflict');
this.aceEditor = ace.edit(elem.nativeElement); // this returns undefined and code further doesnt work
}
What I tried个
我从昨天晚上开始try ,然后用不同的方法在这里提出这个问题,比如:
使用ContentChildren
、ViewContainerRef
、ViewChildren
,甚至使用createEmbeddedView(child.nativeElement)
动态设置模板引用.
我试着研究了聊天GPT,堆栈溢出,但不幸的是,没有对我起作用.
What I want
在sharedCodeEditorChild.component.ts
中,我希望这行this.aceEditor = ace.edit(elem.nativeElement);
能够根据我调用的子实例正确地返回子实例的native-element ,这样两个编辑器就可以显示从父实例传递来的两个不同的JSON值,也可以使用单个sharedCodeEditorChildComponent
单独配置它们.
如果你能指引我正确的方向,这将是非常有帮助的,也会拯救我的一天.谢谢.
UPDATE:如果任何人正在寻找答案,那么请看看这里https://stackblitz-starters-gpzdau.stackblitz.io,这是现在工作,根据穆利提供的答案在下面.