Syertim
Syertim

Reputation: 157

Using reactive forms in Angular with services

i'm tryng to make a kind of deckBuilder, i have some cards and decks made of cards, these are the card and deck models

export class Card {
  public name: string;
  public manaCost: number;
  public imagePath: string;

  constructor(name: string, manaCost: number, imagePath: string) {
    this.name = name;
    this.manaCost = manaCost;
    this.imagePath = imagePath;
  }
}

and deck

import { Card } from '../card/card.model';

export class Deck {
  public deckName: string;
  public deckClass: string;
  public deckCards: Card[];

  constructor(deckName: string, deckClass: string, deckCards: Card[]) {
    this.deckName = deckName;
    this.deckClass = deckClass;
    this.deckCards = deckCards;
  }
}

this is the deckService file

import { Deck } from './deck.model';
import { Card } from '../card/card.model';


export class DeckService {

  decks: Deck[] = [

    new Deck("Control Priest", "Priest", [
      new Card("Reno Jackson", 6, "../../assets/img/Reno_Jackson.png"),
      new Card("Abomination", 5, "../../assets/img/Abomination.png"),
      new Card("Blade Flurry", 4, "../../assets/img/Blade_Flurry.png"),
      new Card("Felfire Potion", 6, "../../assets/img/Felfire_Potion.png")
    ]),
    new Deck("Big Spell Mage", "Mage", [
      new Card("Reno Jackson", 6, "../../assets/img/Reno_Jackson.png"),
      new Card("Abomination", 5, "../../assets/img/Abomination.png"),
      new Card("Blade Flurry", 4, "../../assets/img/Blade_Flurry.png"),
      new Card("Felfire Potion", 6, "../../assets/img/Felfire_Potion.png")
    ])
  ];

  newDeck: Deck; // this is undefined when i try to log it


  constructor() {

  }

  getDecks() {
  return this.decks.slice();
}

  addCard(card: Card){
    console.log(this.newDeck)       // why can't access to newDeck? i have to 
                                    //    bind this function? if i log 'this'  
                                    //   i get DeckService as expected
    this.newDeck.deckCards.push(card);

}

addNewDeck(deck: Deck){
  console.log(this.decks);
  this.decks.push(deck);
};

}

i have a reactive form in which i can add cards to a deck choosing the card with a selection, i want to use the newDeck to save the cards from the form and then push the newDeck in the decks array, but newDeck is undefined, is this a binding problem? this is the form .ts file where i use the deckservice

import { Deck } from './../deck/deck.model';
import { DeckService } from "./../deck/deck.service";

import { Component, OnInit } from "@angular/core";
import { FormArray, FormControl, FormGroup, Validators } from "@angular/forms";
import { CardService } from "../card/card.service";
import { Card } from "../card/card.model";
import { Observable } from "rxjs";

@Component({
  selector: "app-create-deck",
  templateUrl: "./create-deck.component.html",
  styleUrls: ["./create-deck.component.scss"]
})
export class CreateDeckComponent implements OnInit {
  cards: Card[];
  classes = [
    "Priest",
    "Mage",
    "Shaman",
    "Rogue",
    "Warrior",
    "Warlock",
    "Druid",
    "Paladin"
  ];

  createDeckForm: FormGroup;
  deckName: FormControl;

  constructor(
    private cardService: CardService,
    private deckService: DeckService
  ) {}

  ngOnInit() {
    this.cards = this.cardService.getCards();
    this.createDeckForm = new FormGroup({
      deckName: new FormControl("Meme Deck"),
      deckClass: new FormControl(),
      deckCards: new FormControl()
    });
  }

    onAddCard(){
      this.deckService.addCard(this.createDeckForm.value);     //this is wrong but the problem is that i can't access to newDeck


    }

  onSubmit() {

    this.deckService.addNewDeck(this.createDeckForm.value);

  }
}

Upvotes: 0

Views: 91

Answers (2)

Syertim
Syertim

Reputation: 157

thanks, i don't know if i have to open another question but i have another problem, this is the .html of the form



<div class="container">
  <div class="row">
    <form [formGroup]="createDeckForm" (ngSubmit)="onSubmit()">

      <label >Deck Name</label>
      <input
        type="text"
        id="deckName"
        formControlName="deckName"
        class="form-control"
      />
      <p>

      </p>
      <hr>
      <label for="deckClass">Deck class</label>
      <select id="deckClass" formControlName="deckClass">
        <option
            *ngFor="let class of classes"
            [value]="class">
            {{class}}
      </option>
      </select>
      <hr>
      <label for="deckCards">Select a Card</label>
      <select formControlName = "deckCards" id="deckCards" name="deckCards">
        <option
            *ngFor="let card of cards"
            [ngValue]="card">
            {{card.name}}
      </option>
    </select>

      <button (click) = "onAddCard()" class="btn btn-primary">Add Card</button>
      <hr>
      <button class="btn btn-primary" type="submit">Submit</button>

    </form>
  </div>
</div>

i have 2 buttons, one for adding cards to the deck and the onSubmit one to add the deck in the deck array but when i click on the addCard one it is like i'm pressing the submit one too

Upvotes: 0

acincognito
acincognito

Reputation: 1743

By

newDeck: Deck;

you just declare the member, but don't initialize it. Therefore its value is undefined. Use:

newDeck: Deck = new Deck(....); // .... are correct values according to its constructor.

instead.

Additionally have a look at this: https://dev.to/satansdeer/typescript-constructor-shorthand-3ibd

Inside your deck.service.ts in line 23 in stackblitz you could use

newDeck: Deck = this.decks[0];

alternatively and it would work, too.

Upvotes: 1

Related Questions