You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.8 KiB

import { Component, Input } from '@angular/core';
import { FormBuilder, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Ingredient, IngredientEntry, Recipe } from '../../cookbook/type';
import { RecipeService } from '../recipe.service';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatButton } from '@angular/material/button';
@Component({
selector: 'app-recipe-add',
standalone: true,
imports: [ReactiveFormsModule, FormsModule, MatFormFieldModule, MatInputModule, MatButton, MatFormFieldModule],
templateUrl: './recipe-add.component.html',
})
export class RecipeAddComponent {
createForm = this.formBuilder.group({
name: ['', Validators.maxLength(256)],
description: ['', Validators.maxLength(512)],
image: '',
selectedIngredient: '',
});
ingredientEntries: IngredientEntry[] = [];
ingredients: Ingredient[] = [{
id: 1,
name: 'Paprika',
}];
selectedFilename: string = '';
#recipeId: number = -1;
@Input()
set id(recipeId: string) {
if (recipeId === undefined) return;
this.#recipeId = parseInt(recipeId);
const recipe = this.recipes.get(this.#recipeId);
if (recipe === null) {
this.router.navigateByUrl('404');
return;
}
this.createForm.patchValue({
name: recipe.name,
description: recipe.description,
});
}
get recipeId() {
return this.#recipeId;
}
constructor(private formBuilder: FormBuilder, private recipes: RecipeService, private router: Router) {}
onSubmit(): void {
if (this.createForm.invalid) {
return;
}
const value = this.createForm.value;
const partial: Omit<Recipe, 'id'> = {
name: value.name!,
description: value.description!,
image: value.image ?? '',
ingredients: this.ingredientEntries,
};
if (this.#recipeId === -1) {
this.recipes.add(partial);
} else {
this.recipes.edit({ id: this.#recipeId, ...partial });
}
this.router.navigateByUrl('recipes');
}
onAddIngredient(): void {
const value = this.createForm.value;
if (!value.selectedIngredient) {
return;
}
const id = parseInt(value.selectedIngredient!);
if (this.ingredientEntries.find((ingredient) => ingredient.idIngredient === id)) {
return;
}
this.ingredientEntries.push({
idIngredient: id,
idRecipe: -1,
quantity: 1,
});
}
onFileSelected(event: Event): void {
const file = (event.target as HTMLInputElement).files![0];
if (file) {
this.selectedFilename = file.name;
const reader = new FileReader();
reader.onload = (event) => {
this.createForm.patchValue({
image: event.target!.result?.toString()
});
}
reader.readAsDataURL(file);
}
}
}