在angular 1中,我可以将任何元素定义为root元素,并且不能替换任何已编写的内联HTML。
例如 Angular 1。

<body>
  <div ng-app="">
    <h1><?php echo $heading_this_page;?></h1>
    <p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
    <h1>Hello {{name}}</h1>
</div>
</body>

但是在 Angular 2中,如果我在上面这样写的话。
<body>
  <ng-app>
    <h1><?php echo $heading_this_page;?></h1>
    <p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
    <h1>Hello {{name}}</h1>
</ng-app>
</body>

我将ng-app用作主/根组件选择器,ng-app元素的innerHTML被组件的HTML取代。
@Component({
  selector: 'ng-app',
  template:'<h1>App works</h1>";
  directives: [UsersComponent]
})

ng-app的innerHtml现在变为<h1>App works</h1>。我希望保留ng-app的先前内容。

如果这不可能,我可以做下面的事情。
<body>
      <ng-app>
        <h1><?php echo $heading_this_page;?></h1>
        <p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
        <h1>Hello {{name}}</h1>
        <render-component-here></render-component-here>
    </ng-app>
    </body>

其中ng-app是我的主要组件(在加载时引导),它应该在<render-component-here></render-component-here>元素中呈现其数据(而不是通过替换以前的内容本身)

最佳答案

在组件模板中添加<ng-content></ng-content>

@Component({
  selector: 'ng-app',
  template:'<div><h1>App works</h1><ng-content></ng-content></div>';
  directives: [UsersComponent]
})

检查toddmotto说明

请记住,在root组件(正在被引导的组件)中包含文本将不适用于ng-content
<body>
    <ng-app>loading...</ng-app>
</body>

NgApp组件
@Component({
  selector: 'ng-app',
  template: `
    <h1>App component</h1>
    <my-apps>This is the text by ng-content</my-apps>
    <ng-content></ng-content>

  `,
})

将所有其他组件中的内容都可以使用。

检查工作plunker

loading ... index.html中的将始终被ng-app组件替换

因此,即使您提到的<ng-content></ng-content>也不起作用,您的情况也一样。如果要包含它,还必须具有另一个父组件,并且必须具有<ng-app>,现在,在<ng-app>中,您需要具有<ng-content>

10-07 20:01
查看更多