Угловой раскрывающийся список не отображается

Кажется, у меня есть еще одна проблема, связанная с тем, что данные не отображаются для моего выбора коврика в имени группы мышц, хотя мой вызов API подтягивает базу данных к моему компоненту. Я уверен, что все, что мне не хватает, вероятно, довольно просто, поэтому, надеюсь, кто-то сможет это заметить.

Я знаю о других проблемах в коде, таких как моя форма, и о некоторых других вещах прямо сейчас, просто пытаясь получить данные для отображения.

HTML:

      <p>add-exercise works!</p>

<form class="contentContainer" [formGroup]="editFieldsForm" (ngSubmit)="submitEdit()">
    <div fxLayout="column">
        <div fxLayout="row"
            fxLayoutGap="20px"
            fxlaypitAlign="space-between"
            fxjLayout.sm="column"
            fxLayout.xs="column">
            <div fxFlex="1 1 auto">
                <mat-form-field class="fullWidthField">
                    <mat-label>Exercise Name</mat-label>
                    <input type="text" matInput formControlName="exerciseName" required/> 
                </mat-form-field>
            </div>

            <div fxFlex="1 1 auto">
                <mat-form-field appearance="fill">
                    <mat-label>Muscle Group</mat-label>
                    <mat-select>
                    <mat-option *ngFor="let muscleGroup of muscleGroups" [Value]="muscleGroup">
                        {{muscleGroup}}
                    </mat-option>
                    </mat-select>
                </mat-form-field>
            </div>

        </div>
    </div>
    <div fxLayout="row" fxLayoutAlign="center" fxLayoutGap="25px">
        <div>
            <button type="submit" mat-raised-button [disabled]="editFieldsForm.invalid">Submit</button>
        </div>
        <div>
            <button type="button" mat-raised-button (click)="cancelEdit()">Cancel</button>
        </div>
    </div>
</form>

TS

      import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { finalize } from 'rxjs/operators';

import { IExercises } from 'src/app/models/IExcercises';
import { IMuscleGroups } from 'src/app/models/IMuscleGroups';
import { WorkoutService } from 'src/app/services/workout.services';

@Component({
  selector: 'app-add-exercise',
  templateUrl: './add-exercise.component.html',
  styleUrls: ['./add-exercise.component.css']
})
export class AddExerciseComponent implements OnInit {

  @Input() exerciseData: IExercises;
  @Output() editClosed = new EventEmitter();
  @Output() recordUpdated = new EventEmitter<boolean>();
  saving = false;
  updatedexerciseData: IExercises;
  errorMessage = '';
  isLoadingData = false;

  muscleGroup = {} as IMuscleGroups[];

  editFieldsForm: FormGroup;

  constructor(private workoutService: WorkoutService) {   }

  ngOnInit() {
    this.loadDropdown();

    this.editFieldsForm = new FormGroup({
      exerciseName: new FormControl(this.exerciseData.exerciseName, Validators.compose([Validators.required, Validators.maxLength(40)]))
    });
   }

  submitEdit() {
    this.saving = true;
    try {
      this.updatedexerciseData = this.updatedexerciseData;
      this.updatedexerciseData.exerciseId = -1;
      this.updatedexerciseData.exerciseName = this.editFieldsForm.get('exerciseName').value;
      //this.updatedexerciseData.muscleGroupId = getMuscleGroupId(this.editFieldsForm.get('muscleGroupName').value);
    }
    catch (error) {
      console.error(error);
      this.errorMessage = 'An error prevented the record from being submitted.';
      this.saving = false;
      return;
    } 

    this.workoutService.updateExercises(this.updatedexerciseData)
    .pipe(
      finalize(() => { this.saving = false })
    )
    .subscribe(
      () => this.completeFormSubmission(),
      (error: Error) => this.errorMessage = error.message
    );
  }

  completeFormSubmission() {
    this.editClosed.emit();
    this.recordUpdated.emit(true);
  }

  cancelEdit() {
    this.editClosed.emit();
  }

  loadDropdown() {
    this.workoutService.getMuscleGroups().pipe(
      finalize(() => this.isLoadingData = false)
    )
      .subscribe((muscleGroupsData: IMuscleGroups[]) => {
        this.muscleGroup = muscleGroupsData;
        console.log(this.muscleGroup);
      },
        (error: Error) => this.errorMessage = error.message);
    }
}

1 ответ

Решение

Проблема 1. Неправильное название для

Как объяснение в комментарии, в HTML вы повторяете для генерации.

      <mat-option *ngFor="let muscleGroup of muscleGroups" [Value]="muscleGroup">
  {{muscleGroup}}
</mat-option>

Но переменная не найдена в. И вы называете переменную как.


Проблема 2: недопустимое свойство Input для

Вы получите это сообщение об ошибке при использовании [Value] в <map-option>:

Невозможно выполнить привязку к «Value», так как это не известное свойство «mat-option».


Решение

  1. Переименовать в muscleGroups в AddExerciseComponent.
  2. Изменить на [value] для <mat-option>.
  3. (Необязательно) Не ​​отображать с {{muscleGroup}}. Это отобразит [object Object]в HTML. Либо на дисплее укажите свойство из muscleGroup или используйте json труба для отображения всего объекта.

add-training.component.ts

      <mat-option *ngFor="let muscleGroup of muscleGroups" [value]="muscleGroup">
  {{muscleGroup | json}}
</mat-option>

add-training.component.ts

      export class AddExerciseComponent implements OnInit {

  ...

  muscleGroups = {} as IMuscleGroups[];

  loadDropdown() {
    this.workoutService
      .getMuscleGroups()
      .pipe(finalize(() => (this.isLoadingData = false)))
      .subscribe(
        (muscleGroupsData: IMuscleGroups[]) => {
          this.muscleGroups = muscleGroupsData;
          console.log(this.muscleGroups);
        },
        (error: Error) => (this.errorMessage = error.message)
      );
  }
}

Пример решения на StackBlitz

Другие вопросы по тегам