【问题标题】:How to keep previous content of my main component preserved in Angular 2?如何将我的主要组件的先前内容保留在 Angular 2 中?
【发布时间】:2017-06-21 19:36:06
【问题描述】:

在 Angular 1 中,我可以将任何元素定义为根元素,并且不会替换任何已经编写的内联 HTML。 例如角度为 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 现在变为 &lt;h1&gt;App works&lt;/h1&gt; 。我想保留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 是我的主要组件(加载时引导),它应该在 &lt;render-component-here&gt;&lt;/render-component-here&gt; 元素中呈现其数据(而不是通过替换以前的内容本身)

【问题讨论】:

  • 检查我更新的答案。您会发现在 index.html 中指定的组件中有 ng-content 不起作用

标签: angular angular-template


【解决方案1】:

在你的组件模板中添加&lt;ng-content&gt;&lt;/ng-content&gt;

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

查看toddmotto说明

请记住,在根组件(正在引导的组件)中包含文本不适用于 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... in index.html 将始终替换为ng-app 组件

所以,你在同样的情况下,即使你提到&lt;ng-content&gt;&lt;/ng-content&gt; 它也行不通。如果你想包含它,你必须有另一个父组件,你必须有&lt;ng-app&gt;,现在,在&lt;ng-app&gt;里面你需要有&lt;ng-content&gt;

【讨论】:

    【解决方案2】:

    &lt;ng-content&gt; 是您查询的答案

    修改代码

    发件人:

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

    收件人:

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

    如果您想了解更多关于 ng-content 的信息: https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 2017-10-08
      相关资源
      最近更新 更多