Search code examples
angularngfordom-manipulation

How to resolve my Angular DOM rendering problem


I have this HTML where I want to render all my items in an array and also react to the updates from the service when some item changed (updated partially like a 'name').

The problem come in when I send the update and the service returns the array.slice(), there seems to be some problem because I would be able to see the other items in the array but not the one which I recently updated. The communication between the component and the service works like this. There are three components:

  1. listComponent that renders the array.
  2. editComponent that does the update and edit and sends it to component 3
  3. serviceComponent that have all the arrays and does the CRUD operations. Sends the updated value to the service.

Here is my listComponent.html and its .ts code:

      <div *ngFor="let item of items; let i = index">
        <h4>{{item.heading}}</h4>
        <p>{{item.details}}
          <a [routerLink]="[i]"><span>Link here</span></a>
        </p>
      </div>

The .ts file:

  ngOnInit(): void {
    this.items = this.itemsService.getitems()
    this.subscription = this.itemsService.itemChanged.subscribe((items : Item[]) => {
      this.items = items;
    })
  }

Here's a code snippet of the Service.ts:

export class itemsService {
    itemChanged = new Subject<Item[]>();
    private items: Item[] = [
        new Item(
            'Heading-1',
            'Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis, dignissimos inventore, d.'
        ),
        new Item(
            'Heading-2',
            'Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis')
]

getItems() {
        return this.items.slice();
    }
}
    updateItem(index: number, newItem: Item) {
        this.items[index] = newItem;
        this.itemChanged.next(this.items.slice());
    }

And here is the editComponent.ts:

    onSubmit() {
        if (this.editMode){
            console.log(this.editMode)
            this.itemsService.updateItem(this.id, this.iForm.value);
        } 
}

The id in the editComponent is received from the params.


Solution

  • The problem lies with some naming convention in the forms. For eg.

    <input name = 'name' ngModel name='itemName'>
    

    Here, I thought the 'ngModel name' would be the key of the {object Object} but instead the 'name' is the key.