Home > Software design >  Angular 12 Dynamic User Data
Angular 12 Dynamic User Data

Time:04-10

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>

CodePudding user response:

Angular dont see changes in array and object.

You can use :

this.lists = [...this.lists, {
      name: "test",
      id: "test"
}];
  • Related