【问题标题】:angular2 include external html templateangular2 包含外部 html 模板
【发布时间】:2018-10-26 17:53:08
【问题描述】:

有没有办法包含外部 html 文件,我一直无法使用 templateUrl,它一直将 base 附加到 url 的开头。

@Component({
  selector: 'enroll-header',
  templateUrl: 'http://blank.blank.com/somecool.html'
})

它会尝试在"./http://blank.blank.com/somecool.html"找到它

失败了

【问题讨论】:

标签: angular


【解决方案1】:

不支持在 templateURL 中使用外部 URL(可能是因为它会使您面临安全风险)。作为一种解决方法,您可以将模板与您的组件结合使用并显示单个变量。然后您可以将变量设置为等于您要呈现的 html。请检查这两个类似的 SO 问题:

【讨论】:

    【解决方案2】:

    我相信所有的 templateUrl 都是相对于你的应用程序的根目录,所以我认为这行不通。

    【讨论】:

      【解决方案3】:

      我最终使用抓取作业来获取新的 html 文件,然后在我的 index.html 文件中添加了一个服务器端包含命令来附加它们。

      【讨论】:

        【解决方案4】:
        import { Directive, ElementRef, Input, OnInit } from '@angular/core';
        import { Headers, Http, Response } from '@angular/http';
        
        @Directive({ selector: 'ngInclude' })
        export class NgIncludeDirective implements OnInit {
        
        @Input('src')
        private templateUrl: string;
        @Input('type')
        private type: string;
        
        constructor(private element: ElementRef, private http: Http) {
        
        }
        parseTemplate(res: Response) {
            if (this.type == 'template') {
                this.element.nativeElement.innerHTML = res.text();
            } else if (this.type == 'style') {
                var head = document.head || document.getElementsByTagName('head')[0];
                var style = document.createElement('style');
                style.type = 'text/css';
                style.appendChild(document.createTextNode(res.text()));
                head.appendChild(style);
            }
        }
        handleTempalteError(err) {
        
        }
        ngOnInit() {
            //Loads the HTML and bind it to the view
            this.
                http.
                get(this.templateUrl).
                map(res => this.parseTemplate(res)).
                catch(this.handleTempalteError.bind(this)).subscribe(res => {
                    console.log(res);
                });
        }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-11
          • 2020-05-23
          • 1970-01-01
          • 1970-01-01
          • 2020-12-12
          相关资源
          最近更新 更多