0

I am trying to convert myself from knockoutjs, but i am struggling with how dynamic data/observables work in angular 12.

I want to be able to prepopulate an array with some data from a service, but also be able to have that data added to by the user on the page. Using observables how i know them from kockout doesnt seem to be possible.

My code as it is does show the data from the service, but the UI does not change when i click the button. What am i missing to allow this to happen?

import { Component, OnInit } from '@angular/core';
import { List } from '../_models/list.model';
import { ListService } from '../_services/list.service';

@Component({
  selector: 'app-list-admin',
  templateUrl: './list-admin.component.html',
  styleUrls: ['./list-admin.component.less']
})
export class ListAdminComponent implements OnInit {

  lists?: List[];

  constructor(private listService: ListService) { }

  ngOnInit(): void {
    this.listService.getLists().subscribe(res => {
      this.lists = res.lists;
    });
  }

  testEvent(): void {
    this.lists?.push({
      name: "test",
      id: "test"
    });
  }
}
<div *ngFor="let list of lists">
    {{ list.name }}
</div>

<button (click)="testEvent()">test</button>

1

1 Answer 1

1

Angular dont see changes in array and object.

You can use :

this.lists = [...this.lists, {
      name: "test",
      id: "test"
}];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.