Angular2组件——从索引页渲染html

Angular2 component - render html from the index page

本文关键字:html 索引 组件 Angular2      更新时间:2023-09-26

是否有可能在app-nav标签内呈现html,而不是在templateUrl中提供它?

@Component({
  selector: 'app-nav',
  // commented out - templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss']
})
export class NavComponent {
  title: string = 'This is my title';
}

已经在Html页面上的Html。

<app-nav>
  nav works! {{ title }}
</app-nav>

如果我取消注释templateUrl然后app-nav将被nav-component.html页面取代,但我不希望那样。我有动态html,我想渲染它。

您可以使用ngTemplateOutlet投影嵌入视图。在<template><app-nav>标签中包装你的内容。然后在NavComponent中找到TemplateRefContentChild,并将这个templateRef插入到组件的模板中,传递包含标题变量的上下文。像这样:

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss']
})
export class NavComponent {
  title: string = 'This is my title';
  @ContentChild('defaultTemplate') defaultTemplate = null // get templateRef
}

在nav.component.html中创建模板出口和相对模板上下文

<template [ngOutletContext]="{ title: title }" [ngTemplateOutlet]="defaultTemplate"></template>
....other component content....

然后在组件使用的地方:

<app-nav>
  <template #defaultTemplate let-title="title">
    nav works! {{ title }}
  </template>
</app-nav>

乌利希期刊指南:

这里有一个示例

app/some.component.ts中有app/app.component.ts templatengTemplateOutlet投影

乌利希期刊指南:

好的,有一种方法可以将index.html中的初始内容获取到组件中。您可以使用APP_INITIALIZER函数,该函数将在应用程序初始化时执行。

在这里

  1. 参见app/root-template.initializer.ts
  2. app/app.component.ts中,我只是将相关属性替换为初始内容。这是一个有点粗糙的方式,应该通过替换ComponentMetadata中的模板来完成,该模板是用Reflect.getMetadata:

    获得的。
    const annotations = Reflect.getMetadata('annotations', NavComponent)
    const meta = annotations.find(annotation => annotation instanceof ComponentMetadata)
    meta.template = meta.template.replace(
      '{{ someVarInTemplate }}',
      'initialContentInIndex'
    )
    

这样,组件模板就会有初始的索引内容,并被angular解析。更多关于Reflect的信息

@Yaroslav,扩展您的解决方案:

  1. 看起来像一个透传(在Angular 1中),所以在Angular 2中,你可以在内部组件中使用ng-content。

    <div class="my-component">
      <ng-content></ng-content>
    </div>
    
  2. 要在外部跨包标记上进行插值,请给元素一个id并将其作为插值内容的前缀。

    <my-component #comp>
      This is my transcluded content! ++{{comp.title}}++
    </my-component>
    
  3. 不要尝试从index.html中跳转,它不是一个有角度的组件,所以它似乎不能作为外部组件工作。如果你使用app.component作为外部组件,另一个my.component作为内部组件,它就可以工作了。

这是你的叉子与变化。plnkr

作为参考,我使用了Todd Motto关于角2透光的优秀文章:参考这里。
angular指南只是模糊地引用了ng-content(带有404的链接),所以我想知道它是否正在消失。可以被ngComponentOutlet ref here

取代