【问题标题】:render tag selector content in angular2在angular2中渲染标签选择器内容
【发布时间】:2017-01-05 20:28:22
【问题描述】:

我正在使用 angular cli 接口来为 init 简单项目探索 angular2 的表面。

我成功创建了项目,但是当我使用 ng generate component test 添加新组件时 组件的创建方式类似于

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {    
  constructor() { }    
  ngOnInit() {
  }    
}

但让我感到困惑的是,我无法在 <test>Loading</test> 选择器下渲染任何东西(加载除外),我在渲染 app-root 后立即放置了 index.html

 <app-root>Loading...</app-root>
 <test>Loading ...</test>

test.component.html
<p>
  test works!
</p>

我在这里做错了什么?

更新: 主模块知道这个组件会导致 angularcli 添加它并且所有导入都会自动

@NgModule({
  declarations: [
    AppComponent, TestComponent
  ],

更新 2:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}

【问题讨论】:

  • 是否包含app.module.ts 中的所有组件?你喜欢什么文件,main.ts,app.module.ts,app.component.ts
  • 是的,所有都包含在 angular cli 工具中。
  • 您的主模块(基本上称为 app.module.ts)需要先了解每个组件,然后才能使用它们。所以正如@CharanCherry 已经提到的,你导入了吗?
  • 你能告诉我app-root组件代码吗?
  • 任何控制台错误?

标签: angular


【解决方案1】:

唯一的原因是您需要引导这两个组件才能将它们都包含在index.html 中。或者您可以引导应用组件并将测试组件包含在应用组件中。

答案1:

app.module.ts

  declarations: [
    AppComponent, 
    TestComponent
  ],
bootstrap: [ AppComponent, TestComponent ]

答案2:

  bootstrap: [ AppComponent ]

然后在应用组件的模板中包含测试组件,即&lt;test&gt;

例如:如果下面是app.component.html 代码

<h1>app component</h1>

改成

<h1>app component</h1>
<test></test>

包含测试组件

【讨论】:

  • 我相信仅引导 AppComponent 是更自然的方式,至少我是这样认为的。那么如何在 appcomponent 中包含测试组件呢?
  • 由于@Charan Cherry 在我之前回答,我也将在这里回答。 @user1765862 您只需将 &lt;test&gt; 标签移动到 app.component.html。只需在组件 html 文件中的某处添加该标记即可。
【解决方案2】:

没必要杀了我....但是您可以尝试删除&lt;app-root&gt;&lt;/app-root&gt;并仅渲染测试,然后尝试您的“测试”是否按原样渲染:)

【讨论】:

  • 你一定是在开玩笑。
  • 这应该不是问题。 Angular 提供在单个模板中使用多个选择器。
  • @user1765862 只是在我的应用程序该组件上显示加载文本,所以我不知道。没必要杀了我 :D Ok Aer0 我相信你。只是对我的应用进行测试,我收到了同样的问题,所以至少可以测试,对吧?
  • @user1765862 你试过了吗?如果它很愚蠢,我会继续删除这个答案;)
【解决方案3】:

在深入了解 plnkr 以及如何设置 Angular 实时示例之后,我得到了答案。基本上,@AJT_82 的回答部分正确。

从 Angular 2 开始,您必须调用框架,您的选择器中的哪一个是您想要引导的根选择器。这部分由app.module.ts 文件中的以下行处理。

  bootstrap: [ AppComponent ]

如您所见,Angular 将尝试引导您的 AppComponent,这基本上意味着它正在尝试将您的 AppComponent 作为(可能有更多)根元素加载到您的 index.html 中。要让 Angular 查找更多模块,您只需添加下一个模块即可。

  bootstrap: [ AppComponent, TestComponent ]

如果您只是引导 AppComponent,您还可以将您的 &lt;test&gt;&lt;/test&gt; 标签移动到 app.component.html 中,这基本上会导致相同的结果。

Plnkr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2017-02-12
    • 2011-06-14
    相关资源
    最近更新 更多