cah1r
cah1r

Reputation: 1969

Angular2 mechanism behind array update

I'm new to Angular2 (started learning weak ago). I'm trying to grasp a concept of observables and data exchange between components.

I created some code where user can input a data in a form.

    <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
      <div class="form-group">
        <input type="string" class="form-control" id="someValue" [formControl]="myForm.controls['someValue']">
      </div>
  <button type="submit">Submit</button>
</form>

This action should:

  1. Update a list of elements

        <ul> <li *ngFor="let val of valsList"> {{ val.someValue }} </li</ul>
    
  2. Show a counter of elements

    {{counter}}

I created a Plunker with an example of what I have.

http://plnkr.co/edit/pkIpmdS2uOmb7Rf4FfAH?p=preview

Now the thing I don't understand is why the list is getting automatically updated. There must be some kind of binding working but what and how exactly ?

Simmilar approach for counter isn't working.

Regards.

Upvotes: 0

Views: 252

Answers (1)

Madhu Ranjan
Madhu Ranjan

Reputation: 17934

You are not using Observable in your application, To know more how component interaction works , you may look here

In the Plunker you are pushing object into valsList hence your grid is updating as it is directly binding to valsList object.

However for counter you are creating a different instace and updating it hence counter component is not picking up the value.

If you wrap counter into object and use it in the component it will work (as you are not creating new instace of counter just updating the existing object)

Check this Plunker!!

Hope this helps!!

Upvotes: 2

Related Questions