Skip to content

Instantly share code, notes, and snippets.

@webmasterdevlin
Last active March 15, 2019 01:10
Show Gist options
  • Save webmasterdevlin/872faaecc69a4808da1b50d7ef58bd19 to your computer and use it in GitHub Desktop.
Save webmasterdevlin/872faaecc69a4808da1b50d7ef58bd19 to your computer and use it in GitHub Desktop.
Angular Smart Component : src/app/heroes/container/heroes.component.ts
import { Component, OnInit } from "@angular/core";
import { Store } from "@ngrx/store";
import { selectHero, State } from "../../reducers";
import { Hero } from "../../models/hero.model";
import * as heroActions from "../../actions/hero.actions";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
@Component({
selector: "app-heroes",
templateUrl: "./heroes.component.html",
styleUrls: ["./heroes.component.css"]
})
/*
* This is a container component
* contains different presentational components
*/
export class HeroesComponent implements OnInit {
editItemUrl: string = "/heroes/edit-hero/";
list$: any;
list: Hero[];
newItemForm: FormGroup;
isShowNewItemForm: boolean = false;
constructor(private store: Store<State>, private fb: FormBuilder) {}
ngOnInit() {
this.formBuilderInit();
this.store.dispatch(new heroActions.LoadHeroes()); // dispatching a LoadHeroes action
this.list$ = this.store.select(selectHero); // picking up the selectHero selector which returns state.heroes
}
onSubmit() {
this.store.dispatch(new heroActions.CreateHero(this.newItemForm.value)); // dispatching a CreateHero action
this.newItemForm.reset();
this.isShowNewItemForm = !this.isShowNewItemForm;
}
showNewItemForm() {
this.isShowNewItemForm = !this.isShowNewItemForm;
}
cancelForm() {
this.isShowNewItemForm = !this.isShowNewItemForm;
}
removeItem(hero: Hero) {
const isConfirmed = confirm(`Delete ${hero.firstName}`);
if (!isConfirmed) return;
this.store.dispatch(new heroActions.DeleteHero(hero)); // dispatching a DeleteHero action
}
private formBuilderInit(): void {
this.newItemForm = this.fb.group({
firstName: ["", Validators.required],
lastName: [""],
house: [""],
knownAs: [""]
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment