首页 > 解决方案 > how to access another view and it's feature on separate screen through angular portal?

问题描述

I Have an angular project with lot's of component.

I am looping one component with array like this :

<body-chart *ngFor="..."></body-chart>

in body-chart component :

<div>
    <canvas id="canvas"></canvas>
    <button (click)="openModal">Full screen</button>
</div>
<modal>
   I want to show same canvas here that is written in above code..
   When user click on full screen , it will open this modal from same component.
</modal>

How can I show this component's view in modal as well as in other screen by using it's tag ()

Anyone have any idea about it ? then please mention here.

Note :

canvas tag is managed by library, So library automatically add some divs and canvas into same container in which I put canvas tag and render dynamic UI in dom. and it is also interactive.

I tried to use it with ng-template and ng-container like this but in ng-container, my canvas can't interact with mouse and all that stuff

What I have tried :

<ng-template #container>
<div>
    <canvas id="canvas"></canvas>
    <button (click)="openModal">Full screen</button>
</div>
</ng-template>
<ng-container *ngTemplateOutlet="container"></ng-container>
<modal>
    <ng-container *ngTemplateOutlet="container"></ng-container>
</modal>

It will render my template both the places. in component and in modal.

but when Template is rendered in modal, dynamically added element by library can't added in modal (non interactive canvas)

I thought that, maybe, angular will compile html tempalte at a single time instead of when modal is open. that's why dynamically added element are not rendered in the modal.

Another Concept I found is angular portal :

I tried to use angular portal with templatePortal and component portal but failed Due to some wierd error like : can not append of undefined from portal.js

IS there any proper way to do this kind of scenario. please help me.

标签: angulartemplatescontainersportal

解决方案


要在多个位置显示单个内容,您可以利用ng-containerng-template

<ng-template #portal>
  <div>content...</div>
</ng-template>

<div class="place1">
  <ng-container *ngIf="!condition" [ngTemplateOutlet]="portal"></ng-container>
</div>

<div class="place2">
  <ng-container *ngIf="condition" [ngTemplateOutlet]="portal"></ng-container>
</div>

如果我猜对了,模板不会显示在<model>组件内部,因为您正在使用内容投影。

<ng-content select="...">只看第一层的深度。

要解决这个问题,您可以使用ngProjectAs

<modal>
    <ng-container ngProjectAs="container" *ngTemplateOutlet="container"></ng-container>
</modal>

推荐阅读