Adding the component

This one comes in two parts, the HTML template and the class file. Let's start with the class file:

// counter/counter-list/counter-list.component.ts

import { Component, OnInit } from "@angular/core";
import { AppState } from "../../app-state";
import { Store } from "@ngrx/store";
import { addItem, removeItem } from "./counter-list.actions";

@Component({
selector: "app-counter-list",
templateUrl: "./counter-list.component.html",
styleUrls: ["./counter-list.component.css"]
})
export class CounterListComponent implements OnInit {
list$;
newItem: string;
counter: number;

constructor(private store: Store<AppState>) {
this.counter = 0;
this.list$ = this.store.select(state => state.counter.list);
}

ngOnInit() {}

add() {
this.store.dispatch(addItem(this.newItem, this.counter++));
this.newItem = "";
}

remove(id) {
this.store.dispatch(removeItem(id));
}
}

The HTML template file is quite simple, and looks like this:

// counter/counter-list/counter-list.component.html

<div>
<input type="text" [(ngModel)]="newItem">
<button (click)="add()">Add</button>
</div>
<div *ngFor="let item of list$ | async">
{{item.title}}
<button (click)="remove(item.id)">Remove</button>
</div>

In the preceding code, we are supporting the following:

  • Showing a list of counter objects
  • Adding an item to the list
  • Removing an item from the list
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.78.30