【问题标题】:How to get downloaded content data from the root element? Angular2如何从根元素获取下载的内容数据?角2
【发布时间】:2017-06-04 13:28:20
【问题描述】:

经过数小时的谷歌搜索,我没有成功找到解决方案。

我想在文章中添加分享功能。类似于 wordpress 简码之类的东西。所以,里面有Feature内容的内容。文章可以有多个特征。

现在,我明白必须有一个根元素。这就是问题出现的地方。当我将文章放入组件时,内容被组件模板覆盖。

我知道有 ,但这仅适用于根组件。

我希望将文章内容与页面一起加载,以让搜索引擎即使在没有启动 javascript 的情况下也能看到内容。所以,我不想用 REST API 加载内容。

你会如何处理它?我应该如何阅读原始文章,然后如何将其放入角度根元素中?

感谢您的建议!

【问题讨论】:

    标签: javascript angular angular2-template


    【解决方案1】:

    我发现了一个小技巧,但它可能不适用于所有情况。

     @Component({
      selector: 'blog-app',
      template: document.getElementsByTagName('blog-app')[0].innerHTML
    
    })
    
    export class BlogAppComponent {
    
    }
    

    【讨论】:

      【解决方案2】:

      如果您在组件的模板中添加<ng-content></ng-content> 标记会怎样?它应该保留 - 也就是“项目” - 原始内容,不是吗?

      在 Angular 编译之前(这是服务器返回的原始 index.html):

      <body>
        <my-app>
          <p>Some article content</p>
        </my-app>
      </body>
      

      Angular 编译后(这是 Angular 在客户端浏览器中编译后的页面;如果客户端浏览器中禁用 JavaScript,则不会执行此部分):

      <body>
        <my-app>
      
          <!-- Some elements coming from the component's template, e.g. nav... -->
      
          <!-- The NG-CONTENT tag should be replaced by the original content: -->
          <p>Some article content</p>
      
          <!-- More elements coming from the component's template, e.g. footer... -->
      
        </my-app>
      </body>
      

      my-app 的组件将如下所示:

      import { Component } from '@angular/core';
      
      @Component({
        selector: 'my-app',
        template: `
          <!-- navbar elements -->
      
          <ng-content></ng-content>
      
          <!-- footer elements -->
        `,
      })
      export class AppComponent  {}
      

      【讨论】:

      • 我尝试了几种变体,但都不起作用。根据我阅读的一些文章,它甚至不应该工作。 ng-content 仅适用于内部组件。
      • 那么,为什么不添加一个中间组件来让它工作呢?例如&lt;my-app&gt;&lt;inner-comp&gt;&lt;p&gt;YOUR CONTENT&lt;/p&gt;&lt;/inner-comp&gt;&lt;/my-app&gt;
      • 我也试过了,但并没有解决问题。只有当

        YOUR CONTENT

        在 my-app 模板中时,它才会起作用。这不是我的情况。似乎 angular2 还不能做到这一点,这使得它对于非 SPA 项目几乎毫无用处。
      猜你喜欢
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 2020-06-29
      • 2014-03-27
      • 2013-10-17
      • 1970-01-01
      • 2011-05-06
      相关资源
      最近更新 更多