I am a complete newbie in Angular (started learning it yesterday for a take-home job interview project) so I apologize in advance if I’m asking something trivial.
I decided to do a basic project to get some practice: the main component (app) has two children (main-form and answer). main-form collects three numbers a, b and c, computes a+bc and passes the result to answer through app. The problem is, the answer component does not receive the data; instead, both the answer and the warning variable – designed to be invoked when one of the inputs is null – are "undefined". By using the console and test buttons I could see that the values are passed to the parent but not to the sibling component.
I uploaded the entire project to https://github.com/thestraycat7/angular-question/tree/ad44ad0d14d10fa254141d8d30c7a942e258ba15 in case someone would like to help me out. I also used https://medium.com/weekly-webtips/how-to-pass-data-between-components-in-angular-8-c6bfc0358cd2 as an example to follow. Would really appreciate if someone could check my docs and find where the error is.
2
Answers
The reason why the ‘answer’ component does not receive the data is that you put AnswerComponent as part of the bootstrap in the AppModule (I am not sure why you are putting it).
Your app module should be something like this:
Now, the Answer component now is able to receive the data.
We only use bootstrap usually to specify the root component to initiate the Angular application.
This was a tricky one to track down, but the issue actually isn’t related to your component implementation at all, but actually with the setup of the project:
Firstly, some of the contents that belong in
index.html
have been applied toapp.component.html
. The general idea is thatindex.html
will contain the top-level HTML of the webpage, as you would find in a typical vanilla JS project (<html>
,<head>
,<body>
,<script>
etc) and yourapp.component.html
will contain the top level of your application code (basically the contents of the<body
tag)index.html
app.component.html
Secondly, you have this line in
app.module.ts
which needs to be
The
bootstrap
property is used when you need to deploy/switch between two different root applications at the top-level of your projectThat is not required here (and is almost never required for most Angular applications in totality)
Removing this line will treat the
AnswerComponent
as a typical non-root-level component to be included inAppComponent
s component tree. Everything works properly after this change