我是 Angular 的新手(昨天为了一个带回家的工作面试项目开始学习它)所以如果我问的是一些琐碎的事情,我提前道歉。
我决定做一个基础项目来进行一些练习:主要组件(app)有两个子组件(main-form 和 answer)。 main-form收集三个数a、b和c,计算a+bc并通过app将结果传递给answer。问题是,answer 组件没有收到数据;相反,答案和警告变量(设计为在其中一个输入为空时调用)都是“未定义的”。通过使用控制台和测试按钮,我可以看到值被传递给了父组件,但没有传递给同级组件。
我将整个项目上传到https://github.com/thestraycat7/angular-question/tree/ad44ad0d14d10fa254141d8d30c7a942e258ba15以防有人愿意帮助我。我还使用 https://medium.com/weekly-webtips/how-to-pass-data-between-components-in-angular-8-c6bfc0358cd2 作为示例。如果有人可以检查我的文档并找出错误所在,我将不胜感激。
'answer' 组件没有收到数据的原因是你把 AnswerComponent 作为引导程序的一部分放在 AppModule 中(我不确定你为什么要放它)。
你的应用程序模块应该是这样的:
@NgModule({
declarations: [
AppComponent,
AnswerComponent,
MainFormComponent
],
imports: [
FormsModule,
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,Answer 组件现在可以接收数据了。
我们通常只使用 bootstrap 来指定根组件来启动 Angular 应用程序。
这是一个很难追踪的问题,但这个问题实际上与您的组件实现根本无关,但实际上与项目的设置有关:
首先,
index.html
中的一些内容已被应用到app.component.html
中。一般的想法是 index.html
将包含网页的顶级 HTML,就像您在典型的 vanilla JS 项目(<html>
、<head>
、<body>
、<script>
等)和您的 app.component.html
将包含您的应用程序代码的顶层(基本上是<body
标签的内容)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Experimenting with Angular</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="oinkicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>
app.component.html
<div class="topnav">
<a>A very simple calculator</a>
</div>
...
其次,你在
app.module.ts
中有这条线
bootstrap: [AppComponent, AnswerComponent]
需要
bootstrap: [AppComponent]
当您需要在项目的顶层部署/切换两个不同的根应用程序时,使用
bootstrap
属性
这里不需要(而且对于大多数 Angular 应用程序来说几乎从来不需要)
删除此行会将
AnswerComponent
视为典型的非根级组件,以包含在 AppComponent
的组件树中。此更改后一切正常