【问题标题】:how to check output of particular component on webpage in Angular如何在Angular中检查网页上特定组件的输出
【发布时间】:2020-08-17 12:07:35
【问题描述】:

我是角度的新手。我遇到了有关组件的问题。我创建了一个名为 test 的组件。

当我运行代码时,我得到了正确的输出,但是当我从 app.component.html 中删除标签时,我得到了空白网页作为输出。

这里是test.component.ts的代码

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

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

  constructor() { }

  ngOnInit(): void {
  }

}

这里是test.component.html的代码

测试正常

这里是app.component.html的代码

<app-test></app-test>

请纠正我哪里做错了。是否有必要在 app.component.html 中声明每个组件的每个选择器标记(根 html 代码)

【问题讨论】:

  • 这个问题实在看不懂,看了好几遍
  • 如果您不在模板中使用您的组件(或通过 componentFactory 动态添加它),则不会使用它。那是预期的行为。如果您还没有,我强烈建议您阅读 Angular Tour of Heroes 教程,它涵盖了构建 Angular 应用程序的基础知识。 angular.io/tutorial

标签: angular typescript


【解决方案1】:

当您在 app.component.html 中声明组件标签时,您是在告诉 Angular 编译器在您的网页上呈现该组件,当您删除该标签时,编译器将没有任何内容可呈现,因此它显示为空白页面。

您没有做错任何事情,您只需要决定要在页面上呈现哪些组件。

是的,不仅有必要在 app.component.html 中声明每个组件的每个选择器标记,还需要在您希望它呈现的任何地方声明。

您甚至可以使用 Angular 路由通过路由有条件地显示组件。供参考:https://angular.io/guide/router

【讨论】:

    【解决方案2】:

    在 app.component.html 中添加 selector() 很重要。如果您希望该组件需要可见或不可见。

    就像如果你定义了项目的路由,那么你需要在主组件中添加router-outlet。

    【讨论】:

    • 好吧,你的意思是我必须在 app.component.ts 中声明每个组件的选择器标签,对吧?
    • 不,我们使用 在 app.component.html 中渲染组件
    • 是的,如果你想渲染这个组件,你必须声明这个标签。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2021-03-24
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 2020-01-17
    • 2014-08-04
    相关资源
    最近更新 更多