Angular:带有角度分量动态的JSON html标记

问题描述 投票:0回答:1

编辑1:

感谢@Narm的解决方案。我搞定了!

let myTemplate = '<div class="test" (tap)="test();">Test</div>';,我有一个tap功能。

当我点击它来调用该函数时,它不起作用并给出错误:

ERROR TypeError: _co.another_test is not a function

这是我到目前为止:

ngOnInit(){ 
   ...
    let myTemplate = `<div class="test" (tap)="test();">Test</div>`;
   ...
}

test(){
  console.log("Test");
}

有什么想法吗?


原始问题如下

从PHP使用REST,我得到Angular组件的HTML标记:

来自php:

function send_html(){
    $html = '<div class="test" *ngIf="data">This is an example</div>';
    return $html;
};

然后在我的角度项目中,我试图使用componentFactoryResolver动态添加这个html :(我知道它只接受Angular组件)

这是我的思考过程:

  1. main.ts(如下所示):调用getDynamicREST()并从php获取$html
  2. 获取数据后,将其发送到my_component.ts,使其成为Angular组件。
  3. 一旦html标记成为Angular组件的一部分,然后使用createComponent创建组件。

当然,它不起作用......

这是我到目前为止所做的:请随意拆开它。

main.html中

<div class="top">
   <ng-template #main></ng-template>
</div>

main.ts

import { Component, ViewChild, ComponentFactoryResolver, ViewContainerRef  } from '@angular/core';
import { my_component } from './my_component';

@Component({
    selector: 'page-main_page',
    templateUrl: 'main_page.html'
})
export class main_page {        
    @ViewChild('main', { read: ViewContainerRef }) entry: ViewContainerRef;
    data: any;

constructor(public resolver: ComponentFactoryResolver,
            public mine: my_component ){    

};      

    ngOnInit(){ 
        this.getDynamicREST().then((res)=>{
            this.mine.data = res;

            const factory = this.resolver.resolveComponentFactory(my_component);
            this.entry.createComponent(factory);

        })
    };

}

my_component.ts

import { Component } from '@angular/core';


@Component({
    selector: 'my_component ',
    template: '<div class="my_component">{{data}}</div>'
})

export class my_component {
   data: any;
}

我如何实现这一点,以便我可以动态获取角度组件并显示它们?

任何帮助都感激不尽。

谢谢。

php angular dynamic
1个回答
1
投票

你走在正确的道路上。几个月前我遇到了同样的情况,这是实现目标的解决方案。

如果你想看到现场运行的代码并有机会玩它,我附上了StackBlitz。动态组件起初可能是一个难以理解的挑战。

Live Demo

app.component.ts

此组件充当动态组件的容器,并且是创建它的位置。

import {
  Component, ViewChild, OnInit, OnDestroy,
  AfterViewInit, ComponentFactoryResolver,
  Input, Compiler, ViewContainerRef, NgModule,
  NgModuleRef, Injector
} from '@angular/core';


import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';


@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('vc', { read: ViewContainerRef }) _container: ViewContainerRef;
  private cmpRef;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private compiler: Compiler,
    private _injector: Injector,
    private _m: NgModuleRef<any>) { }

  ngOnInit() { }

  ngAfterViewInit() {
    let myTemplate = `<h2> Generated on the fly</h2>
                      <p>You can dynamically create your component template!</p>`

    @Component({ 
      template: myTemplate 
      })
      class dynamicComponent {
        constructor(){}
    }
    @NgModule({
      imports: [
        BrowserModule
      ],
      declarations: [dynamicComponent]
    })class dynamicModule {};
    const mod = this.compiler.compileModuleAndAllComponentsSync(dynamicModule);
    const factory = mod.componentFactories.find((comp) =>
      comp.componentType === dynamicComponent
    );

    this.cmpRef = this._container.createComponent(factory);
  }

  ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
  }
}

然后在您的应用组件的模板中

app.component.html

<ng-template #vc></ng-template>

然后在app.module中,您需要导入编译器并将其声明为提供者:

app.module.ts

import {Compiler, COMPILER_OPTIONS, CompilerFactory} from '@angular/core';
import {JitCompilerFactory} from '@angular/platform-browser-dynamic';
export function createCompiler(compilerFactory: CompilerFactory) {
  return compilerFactory.createCompiler();
}



@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    routing
  ],
  providers: [
    {provide: COMPILER_OPTIONS, useValue: {}, multi: true},
    {provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS]},
    {provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory]}
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

***编辑“点按”问题

你想要做的是绑定到(点击)事件,我不知道任何(点击)事件,MDN中的事件参考中没有列出任何事件Events Reference MDN

在动态组件中添加以下内容:

let myTemplate = `<h2> Generated on the fly</h2>
                      <p>You can dynamically create your component template!</p>
                      <div class="test" (click)="test();">Test</div>`

    @Component({ 
      template: myTemplate 
      })
      class dynamicComponent {
        constructor(){}

        public test(){
          alert("I've been clicked!");
        }
    }

注意我更新了StackBlitz,如果你想看到它的作用!

© www.soinside.com 2019 - 2024. All rights reserved.