使用变量Angular2访问TemplateUrl

时间:2018-03-15 14:09:18

标签: angular

我在VSCode编辑器中创建一个指令,它在指定给定路径时加载一个html页面:

以下是相同的代码:

@Directive({
selector: 'html-outlet'
 })

export class HtmlOutlet {
@Input() html: string;

constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

ngOnChanges() {
    const html = this.html;
    if (!html) return;

    @Component({
        selector: 'dynamic-comp',
        templateUrl: html
    })
    class DynamicHtmlComponent { };

    @NgModule({
        imports: [CommonModule],
        declarations: [DynamicHtmlComponent]
    })
    class DynamicHtmlModule { }

    this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
        .then(factory => {
            const compFactory = factory.componentFactories.find(x => x.componentType === DynamicHtmlComponent);
            const cmpRef = this.vcRef.createComponent(compFactory, 0);
        });
}}

但是我一直收到以下错误: 错误在./src/client/app/shared/directives/html-outlet.directive.ts 找不到模块:错误:无法解析'D:\ ccw-dev \ newnewclient \ src \ client \ app \ shared \ directives'中的'html'

然而,相同的代码在plunker中工作正常 https://plnkr.co/edit/l8BwjGIMC5tUVjIeh4u4?p=preview

我想知道我在做什么错。我在VScode解决方案中处于角度5.2.6版本。

2 个答案:

答案 0 :(得分:0)

你能试试吗

@Component({
    selector: 'dynamic-comp',
    templateUrl: `${html}`
})
class DynamicHtmlComponent { };

它应该打破角度模板加载器的使用正则表达式(cf Angular 2 - Webpack 2 - template-loader not working with templateUrl

答案 1 :(得分:0)

我能够通过不使用TemplateUrl来解决我的问题。我使用了模板然后我使用innerHtml来分配html。

 @Component({
    selector: 'dynamic-comp',
    template:`
    <div [innerHtml]="myTemplate">
    </div>
    `
  })
  class DynamicHtmlComponent  { 
    private myTemplate: any = "";
    constructor(private http: Http , private sanitizer: DomSanitizer ){
        this.http.get(html).subscribe((html)=>{
            this.myTemplate = sanitizer.bypassSecurityTrustHtml(html.text()) ;               
        })
    }
  };