简体   繁体   English

使用变量Angular2访问TemplateUrl

[英]Access TemplateUrl using variable Angular2

I am creating a directive in VSCode Editor which loads a html page on specifying a given path: 我正在VSCode编辑器中创建指令,该指令在指定给定路径时加载html页面:

Below is the code for same: 下面是相同的代码:

@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);
        });
}}

However I keep getting below error: ERROR in ./src/client/app/shared/directives/html-outlet.directive.ts Module not found: Error: Can't resolve ' html' in 'D:\\ccw-dev\\newnewclient\\src\\client\\app\\shared\\directives' 但是我一直得到以下错误:./src/client/app/shared/directives/html-outlet.directive.ts中的错误找不到模块:错误:无法在'D:\\ ccw-dev \\中解析'html' newnewclient \\ src \\ client \\ app \\ shared \\ directives'

The same code however works fine in plunker https://plnkr.co/edit/l8BwjGIMC5tUVjIeh4u4?p=preview 但是,相同的代码在plunker中工作正常https://plnkr.co/edit/l8BwjGIMC5tUVjIeh4u4?p=preview

I am wondering what wrong i am doing. 我想知道我在做什么错。 I am on angular 5.2.6 version in my VScode solution. 我在VScode解决方案中使用的是angular 5.2.6版本。

Can you try 你能试一下吗

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

It should break the regexp use by the angular template loader ( cf Angular 2 - Webpack 2 - template-loader not working with templateUrl ) 它应该破坏有角模板加载器对正则表达式的使用(请参阅Angular 2-Webpack 2-template-loader不与templateUrl配合使用

I was able to solve my problem by not using TemplateUrl.I used a template then I used innerHtml to assign the the html. 我可以通过不使用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()) ;               
        })
    }
  }; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM