繁体   English   中英

Angular 11 - 模态方法检查数组中的值并返回 false,即使构造函数加载了数组

[英]Angular 11 - Modal Method checks for value in array and returns false even when the constructor loads the array

我有一个表格,注册了一组名为“区域”的新课程。 表单有一个按钮,调用模态 window 并允许用户 select 所需的课程并将它们添加到表单列表中。

最初的 function 似乎工作正常。 当我在 select 一个课程对话框中,课程被添加到父组件数组中。 然后我检查是否已经选择了课程,以便显示取消选择课程的按钮。

问题出在我关闭模态对话框并再次打开它时。 “isCourseSelected”方法(检查“课程”object 是否在数组内)不起作用。 即使构造函数从 modalService 的 initialState 填充数组“modalSelectedCourses”,它也会返回 false。

这是有问题的代码:

import { ChangeDetectorRef, Component, EventEmitter, OnInit, Output } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { FormControl, FormGroup } from '@angular/forms';
import { FileUploadValidators } from '@iplab/ngx-file-upload';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { isThisTypeNode } from 'typescript';
import { Course } from '../../../../shared/models/course.model';

@Component({
  selector: 'app-area-form',
  templateUrl: './area-form.component.html',
  styleUrls: ['./area-form.component.scss'],
})

export class AreaFormComponent implements OnInit {
  public selectedCourses: Course[];
  bsModalRef?: BsModalRef;
  public animation: boolean = false;
  public multiple: boolean = false;
  private filesControl = new FormControl(null, FileUploadValidators.filesLimit(2));

  public demoForm = new FormGroup({
    files: this.filesControl
  });

  constructor(public modalService: BsModalService, private cd: ChangeDetectorRef) {
  }

  get staticSelectedAreas() {
    return this.selectedCourses;
  }

  public processSelection(course: Course) {
    if (this.selectedCourses.indexOf(course) !== -1) {
      this.selectedCourses = this.selectedCourses.filter((curCourse) => course.id !== curCourse.id);
    } else {
      this.selectedCourses.push(course);
    }
    this.cd.markForCheck();
  }

  public toggleStatus(): void {
      this.filesControl.disabled ? this.filesControl.enable() : this.filesControl.disable();
  }

  public toggleMultiple() {
      this.multiple = !this.multiple;
  }

  public clear(): void {
      this.filesControl.setValue([]);
  }

  ngOnInit(): void {
    this.selectedCourses = [];
  }

  openModalWithComponent() {
    const initialState = {
      modalSelectedCourses: this.selectedCourses
  };
    this.bsModalRef = this.modalService.show(CoursesModalComponent, {initialState, class: 'modal-lg'});
    this.bsModalRef.content.notifyParent.subscribe((e) => {
      this.processSelection(e);
    });
    this.bsModalRef.content.closeBtnName = 'Close';
  }

}

@Component({
  selector: 'app-search-courses-list',
  templateUrl: './courses-list-modal.component.html',
  styleUrls: ['./area-form.component.scss'],
})

export class CoursesModalComponent implements OnInit {
  @Output() notifyParent = new EventEmitter<Course>();
  title?: string = 'Buscar Cursos';
  closeBtnName?: string;
  courses: Course[] = [];
  modalSelectedCourses: Course[] = [];

  constructor(public bsModalRef: BsModalRef, firestore: AngularFirestore, public modalService: BsModalService) {
    firestore.collection('courses').valueChanges({idField: 'id'}).forEach((course) => {
      course.forEach((tempCourse) => {
        const newCourse: Course = new Course().deserialize(tempCourse);
        this.courses.push(newCourse);
      });
    });
    this.modalSelectedCourses = this.modalService.config.initialState['modalSelectedCourses'];
    console.log(this.modalSelectedCourses);
  }

  public addSelectedCourse(course: Course) {
    this.notifyParent.emit(course);
    this.modalSelectedCourses.push(course);
  }

  public removeSelectedCourse(course: Course) {
    this.notifyParent.emit(course);
    this.modalSelectedCourses = this.modalSelectedCourses.filter((curCourse) => course.id !== curCourse.id);
  }

  public isCourseSelected(course: Course) {
    if (this.modalSelectedCourses.indexOf(course) !== -1) {
      return true;
    } else {
      return false;
    }
  }

  ngOnInit() {
  }
}

另外,这里是模态模板“courses-list-modal.component”的代码:

<div class="modal-header">
    <h4 class="modal-title pull-left">{{title}}</h4>
    <button type="button" class="btn-close close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
      <span aria-hidden="true" class="visually-hidden">&times;</span>
    </button>
</div>
<div class="modal-body">
    <div class="row">
        <div class="col-sm-8">
            <div class="search-course-div">
                <input type="text" class="form-control search-course-textfield" name="search" placeholder="Buscar curso"><i class="fa fa-search"></i>
            </div>
        </div>
        <div class="col-sm-4">
            <button class="btn btn-primary">+ Crear curso</button>
        </div>
    </div>
    <div class="courses-table">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Nombre del curso</th>
                    <th>Cant. de lecciones</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <ng-container *ngIf="courses; else noCourses">
                    <tr *ngFor="let course of courses">
                        <td>{{ course.name }}</td>
                        <td>##</td>
                        <td>
                            <ng-container *ngIf="isCourseSelected(course); else notSelectedTemplate">
                                <button (click)="removeSelectedCourse(course)" type="button" class="btn btn-primary">Asignado <i class="fa fa-check-circle"></i></button>
                            </ng-container>
                            <ng-template #notSelectedTemplate>
                                <button (click)="addSelectedCourse(course);" type="button" class="btn btn-outline-primary">Asignar</button>
                            </ng-template>

                        </td>
                    </tr>
                </ng-container>
                <ng-template #noCourses>
                    <tr>
                        <td colspan="3">No hay cursos disponibles</td>
                    </tr>
                </ng-template>

            </tbody>
        </table>
    </div>
</div>

我不知道为什么该方法在我第二次打开对话框时返回 false。

预先感谢您对我们的支持!

我认为的解决方法是使“selectedCourses”成为 static 变量。 它不起作用,因为“isCourseSelected”方法中的 this.modalSelectedCourses 在初始化时始终为空。 因此,创建变量 static,它将保留 memory 上的数据并检查实际数组值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM