【问题标题】:Dynamically convert a angular component to HTML将角度组件动态转换为 HTML
【发布时间】:2019-08-01 12:55:08
【问题描述】:

我希望在元素内单击按钮时呈现模板我已将该模板创建为单独的组件(自定义组件),因为它可以多次使用。因此,当我单击希望将此自定义组件编译为作为 HTML 字符串返回时,因为我需要使用字符串处理某些内容并发送 html 字符串。有角度有可能吗?

示例代码(只是为了解释我的情况)

import { templatecomponent } ./template.component

...

onButtonClick(): any
{
  return compile(templatecomponent) // return the html from the template component
}

【问题讨论】:

标签: angular angular-template


【解决方案1】:

我认为你不能像上面那样使用它!您有用于组件和条件检查的选择器。如果你的组件将被调用,你可以使用条件检查来检查按钮的点击

Custom.component.ts 

    @Component({
       selector: "custom-app",
       template: `I am from custom component`,
       style: ""
    })

Calling.component.ts

     @Component({
           selector: "calling-app",
           template: `<button (click)="customFn()">Show custom</button>
                       <custom-app *ngIf="isCustom"></custom-app>
                      `,
           style: ""
     })

    export class CallingComponent{
            isCustom: false
            constructor(){}
            customFn(){
                this.isCustom =  !this.isCustom
            }
     }

别忘了配置模块

【讨论】:

    【解决方案2】:

    您可以创建一个渲染组件,它将视图附加到它自己的视图,然后返回内部 HTML。

    唯一的问题是组件必须在 页面外 呈现,因为视图必须附加到 DOM,并且您必须使用 setTimeout() 来允许子组件 时间 完成渲染。

    或者,您可以使用ngTemplate 引用而不是组件工厂。附加到ViewContainerRef 时,两者基本相同。

    这是我写的一个例子,但我没有尝试过:

    @Component({
       selector: 'app-render',
       template: '',
       styles: [
           'position: absolute',
           'top: -99999',
           'left: -99999'
       ],
       exportAs: 'appRender'
    })
    export class RenderComponent {
        constructor(private view: ViewContainerRef,
                    private el: ElementRef<HTMLElement>) { }
    
        public function compile(factory: ComponentFactory<any>): Promise<string> {
            return new Promise(resolver => {
                this.view.createComponent(template);
                setTimeout(() => {
                     resolver(this.el.nativeElement.innerHTML);
                     this.view.clear();
                });
            });
        }
    }
    

    你必须在你的应用中添加&lt;app-render&gt;组件somewhere,然后调用compile(myComponent),它会返回一个带有HTML字符串的promise。

    如果您的 child 组件使用*ngIf*ngFor 则需要增加setTimeout() 的持续时间,或者您调用多个setTimeout() 函数。无论哪种方式,您都需要时间让 Angular 呈现 HTML。

    不可能使用不同的方法来创建从组件生成 HTML 作为字符串的同步函数。 Angular 不能那样工作。

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多