【问题标题】:Access TemplateUrl using variable Angular2使用变量 Angular2 访问 TemplateUrl
【发布时间】:2018-03-20 18:20:40
【问题描述】:

我正在 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 解决方案中使用 Angular 5.2.6 版本。

【问题讨论】:

  • 您是在运行时还是在构建应用程序时收到此错误?因为这可能是 angular2-template-loader 之类的插件的副作用
  • 我在 ng-build 本身上收到此错误

标签: angular


【解决方案1】:

你可以试试

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

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

【讨论】:

    【解决方案2】:

    我能够通过不使用 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()) ;               
            })
        }
      }; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 2017-06-15
      • 1970-01-01
      • 2016-06-12
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多