首页 文章

如何在Angular 2中保留我的主要组件的先前内容?

提问于
浏览
3

在角度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>

但是在角度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> 元素中呈现其数据(而不是通过替换以前的内容本身)

2 回答

  • 2

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

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

    检查toddmotto说明

    Remember that having text in root component(component that is being bootstrapped) will not work with 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>
    
      `,
    })
    

    Having content in all other components will work.

    检查工作plunker

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

    所以,你是在同样的情况下,即使你提到 <ng-content></ng-content> 它也行不通 . 如果你想包括那个你也必须有另一个父组件,你必须有 <ng-app> 现在,在 <ng-app> 内你需要 <ng-content>

  • 3

    <ng-content> 是您的查询的答案

    改变你的代码

    From :

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

    To :

    @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

相关问题