Angular: Two way binding and Event binding not working

50 Views Asked by At

I am very new to angular and am learning through the Heroes tutorial. I am on the part concerning two-way binding. I have learned all the different binding types and tried to implement them. Interpolation and property binding work fine. However, when I tried two-way binding (and event binding) in the file that was specified in the tutorial with the correct imports as well. So that someone is able to see it. The HTML file is heroes.component.html and it is the template for heroes.component.ts with the component name app-heroes, which is called in app.component.html The elements are on the bottom of the webpage.

I have tried using the event binding within the app.component (ts and HTML), and it seems to work (blue button), but not the two-way binding which is below the blue button (hero age). neither of these two work with the heroes component (Hero Name and Hello Button).

The working link is in the comments, wouldn't work when pasting it on the post for some reason

Apologies if any confusing wording and Thank You!

1

There are 1 best solutions below

3
Blake On BEST ANSWER

Remember: an HTML document should have only one <body> element

Remove <body></body> from heroes.component.html. After your two way bonded hero.name will work. You refer to a "blue button" but that is not in the provided Stackblitz (see img below).

I found this by viewing the console logs within stackblitz. From there you see there is a hydration issue and checking the html is a proposed solution.

We only want <body></body> in one place, in index.html

Error for reference:

Error: NG0500: During hydration Angular expected <body> but found <h2>.

Angular expected this DOM:

<app-heroes _ngcontent-ng-c2099804242="" _nghost-ng-c3944397914="">
  <body>…</body>  <-- AT THIS LOCATION
  …
</app-heroes>

Actual DOM is:

<app-heroes _ngcontent-ng-c2099804242="" _nghost-ng-c3944397914="">
  <h2 _ngcontent-ng-c3944397914="" style="color:#2D2E2E;">…</h2>  <-- AT THIS LOCATION
  …
</app-heroes>

Note: attributes are only displayed to better represent the DOM but have no effect on hydration mismatches.

To fix this problem:
  * check the "_HeroesComponent" component for hydration-related issues
  * check to see if your template has valid HTML structure
  * or skip hydration by adding the `ngSkipHydration` attribute to its host node in a template

 Find more at https://angular.io/errors/NG0500

Stackblitz project