加载Firebase下拉菜单,保存已选择的选项以进行角度编辑

问题描述

我想将选择的下拉列表数据上传到模板进行编辑。我使用变量nombre来解决这个问题,一切都保存在firebase中,没有问题。我要在输入新值时在“”中初始化下拉变量,但是当我单击编辑时,我想在保存在firedatabase中的所选项目中初始化下拉变量。

.ts

export class RecipeEditComponent implements OnInit,OnDestroy {
  public selectedAsset:TiposdeActivo={nombre:''};
  public tipos : TiposdeActivo [];


  id: any;
  nombre: string;
  codigointerno:number;
  tiposdeActivo: any
  editMode = false;
  recipeForm: FormGroup;

  private storeSub: Subscription;

  get ingredientsControls() {
    return (this.recipeForm.get('ingredients') as FormArray).controls;
  }

  constructor(
    private route: ActivatedRoute,private router: Router,private store:Store<fromApp.AppState>,private dataSvc: DataService,) {}

  ngOnInit() {

    this.tipos = this.dataSvc.getTypes();
    this.route.params.subscribe((params: Params) => {
      this.id = +params['id'];
      this.nombre= params['nombre'];
      this.editMode = params['id'] != null;
      this.initForm();
    });
  }

  onSubmit(userForm:NgForm) {
   

    if (this.editMode) {
     /*  this.recipeService.updateRecipe(this.id,this.recipeForm.value); */

    this.store.dispatch(new RecipesActions.UpdateRecipe({
      index:this.id,newRecipe: this.recipeForm.value,})
    );
    } else {
      /* this.recipeService.addRecipe(this.recipeForm.value); */
      this.store.dispatch(new RecipesActions.AddRecipe(this.recipeForm.value))
    }


    this.onCancel();
  }

  onAddIngredient() {
    (<FormArray>this.recipeForm.get('ingredients')).push(
      new FormGroup({
        name: new FormControl(null,Validators.required),amount: new FormControl(null,[
          Validators.required,Validators.pattern(/^[1-9]+[0-9]*$/)
        ])
      })
    );
  }

  onDeleteIngredient(index: number) {
    (<FormArray>this.recipeForm.get('ingredients')).removeAt(index);
  }

  onCancel() {
    this.router.navigate(['../'],{ relativeTo: this.route });
  }

  ngOnDestroy(){
    if(this.storeSub){
    this.storeSub.unsubscribe();
  }
}

  private initForm() {
    let recipeName = '';
    let recipeImagePath = '';
    let recipeDescription = '';
    let recipeCodigoIntero ='';
    let recipeTiposdeActivo=this.selectedAsset;
    let recipeIngredients = new FormArray([]);

    if (this.editMode) {
      /* const recipe = this.recipeService.getRecipe(this.id); */
      this.storeSub = this.store.select('recipes').pipe(map(recipeState=>{
        return recipeState.recipes.find((recipe,index)=>{
          return index === this.id

        })
      })).subscribe(recipe =>{
        recipeName = recipe.name;
        recipeImagePath = recipe.imagePath;
        recipeDescription = recipe.description;
        recipeCodigoIntero=recipe.codigointerno;
        recipeTiposdeActivo['nombre']=recipe.tiposdeActivo;
        if (recipe['ingredients']) {
          for (let ingredient of recipe.ingredients) {
            recipeIngredients.push(
              new FormGroup({
                name: new FormControl(ingredient.name,amount: new FormControl(ingredient.amount,[
                  Validators.required,Validators.pattern(/^[1-9]+[0-9]*$/)
                ])
              })
            );
          }
        }
      })

    }

    this.recipeForm = new FormGroup({
      name: new FormControl(recipeName,imagePath: new FormControl(recipeImagePath,description: new FormControl(recipeDescription,ingredients: recipeIngredients,TiposdeActivo: new FormControl(recipeTiposdeActivo,codigointerno: new FormControl(recipeCodigoIntero,Validators.required)
    });
  }
}

.html

<hr>
<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="recipeForm" (ngSubmit)="onSubmit()">
      <div class="row">
        <div class="col-xs-12">
          <button
            mat-button
            type="submit"
            class="btn btn-success"
            [disabled]="!recipeForm.valid"
          >
            Save
          </button>
          <button type="button" class="btn btn-danger" (click)="onCancel()">
            Cancel
          </button>
        </div>
      </div>
      <form>

        <div class="form-group">
          <label for="exampleFormControlSelect1">Tipos de Activo</label>
          <select class="form-control"  [(ngModel)] ="selectedAsset.nombre"  [ngModelOptions]="{standalone: true}">

            <option *ngFor="let tipo of tipos" formControlName="nombre"  [value]="tipo.nombre" >{{tipo.nombre}}
            </option>
          </select>

        </div>
      </form>
      <div class="row">
        <div class="col-xs-12">
          <div class="form-group">
            <label for="codigointerno">Codigo Interno</label>
            <input
              type="text"
              id="codigointerno"
              formControlName="codigointerno"
              class="form-control"
            />
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <div class="form-group">
            <label for="name">Name</label>
            <input
              type="text"
              id="name"
              formControlName="name"
              class="form-control"
            />
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-xs-12">
          <div class="form-group">
            <label for="imagePath">Image URL</label>
            <input
              type="text"
              id="imagePath"
              formControlName="imagePath"
              class="form-control"
              #imagePath
            />
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <img [src]="imagePath.value" class="img-responsive" />
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <div class="form-group">
            <label for="description">Description</label>
            <textarea
              type="text"
              id="description"
              class="form-control"
              formControlName="description"
              rows="6"
            ></textarea>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12" formArrayName="ingredients">
          <div
            class="row"
            *ngFor="let ingredientCtrl of ingredientsControls; let i = index"
            [formGroupName]="i"
            style="margin-top: 10px;"
          >
            <div class="col-xs-8">
              <input type="text" class="form-control" formControlName="name" />
            </div>
            <div class="col-xs-2">
              <input
                type="number"
                class="form-control"
                formControlName="amount"
              />
            </div>
            <div class="col-xs-2">
              <button
                type="button"
                class="btn btn-danger"
                (click)="onDeleteIngredient(i)"
              >
                X
              </button>
            </div>
          </div>
          <hr />
          <div class="row">
            <div class="col-xs-12">
              <button
                type="button"
                class="btn btn-success"
                (click)="onAddIngredient()"
              >
                Add Ingredient
              </button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

data.service.ts

import { Injectable } from '@angular/core';
import {TiposdeActivo} from '../models/model.interface';

@Injectable()
export class DataService {

private tipos: TiposdeActivo[] = [
  {

    nombre:'Terrenos'
  },{

    nombre:'Mobiliario'
  },{

    nombre:'Maquinaria'
  },{

    nombre:'Equipos e Instalaciones'
  },{

    nombre:'Vehiculos'
  },];

  getTypes(): TiposdeActivo[]{
    return this.tipos;
  }

}

recipe.model.ts

import { Ingredient } from '../shared/ingredient.model';
import {TiposdeActivo} from './recipe-edit/models/model.interface'



export class Recipe {

  public nombre: string;
  public name: string;
  public description: string;
  public imagePath: string;
  public tiposdeActivo: TiposdeActivo['nombre'];
  public ingredients: Ingredient[];
  public codigointerno:any;

  constructor(name: string,desc: string,imagePath: string,ingredients: Ingredient[],tiposdeActivo: TiposdeActivo['nombre'],nombre: string,codigointerno:any) {

    this.nombre=nombre;
    this.name = name;
    this.description = desc;
    this.imagePath = imagePath;
    this.codigointerno = codigointerno;
    this.tiposdeActivo=tiposdeActivo;
    this.ingredients = ingredients;

  }
}

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)