Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

284
Views
No se pueden agregar elementos predeterminados al menú desplegable angular

Estoy tratando de mostrar algunos datos seleccionados por defecto en mi menú desplegable angular, pero por alguna razón, si push() los elementos desde el interior del método de subscribe() , los elementos no se seleccionan y si intento agregar los elementos fuera de este específico el método de suscripción agrega los elementos al menú desplegable sin ningún problema.

NOTA: si registro mi matriz, me da todos los elementos, incluidos los elementos que agregué desde dentro de subscribe()

Parte de mi componente:

 public students = [] public loadedSelectedStudents = [] public selectedStudents = [] // Get all selected students this.studentService.getStaffStudents(+loadedUserId).subscribe(async selectedStudents => { for (var i = 0; i < selectedStudents.length; i++) { var selectedStudentId: number = selectedStudents[i].studentId var studentModel: StaffStudentModel = new StaffStudentModel() studentModel.userId = +loadedUserId studentModel.studentId = selectedStudentId var resStudent: StudentModel = await this.studentService.getStudent(selectedStudentId).toPromise() // THIS IS NOT WORKING this.loadedSelectedStudents.push({ student_id: studentModel.studentId, student_name: resStudent.name }) this.selectedStudents.push({ student_id: studentModel.studentId, student_name: resStudent.name}) this.changeDetectorRef.detectChanges(); } }) // THIS IS WORKING this.selectedStudents.push({student_id: 5, student_name: "Jonh"})

Parte de mi servicio:

 getStaffStudents(userId: number) : any { return this.http.get<StudentModel[]>(this.baseUrl + 'Api/GetStaffStudents/' + userId).pipe(map(res => res)) }

Mi configuración desplegable y FormGroup:

 this.studentsDropDownSettings = { idField: 'student_id', textField: 'student_name', allowSearchFilter: true, noDataAvailablePlaceholderText: "No Available Students" } this.studentsDropDownForm = this.fb.group({ studentsItems: [this.selectedStudents] });

Y mi elemento HTML:

 <div *ngIf="showStudensMenu" class="form-group"> <form [formGroup]="studentsDropDownForm"> <label for="exampleFormControlSelect1">Students *</label> <ng-multiselect-dropdown [settings]="studentsDropDownSettings" [data]="students" (onSelect)="onStudentSelected($event)" (onSelectAll)="onAllStudentsSelected()" (onDeSelect)="onStudentDeSelected($event)" (onDeSelectAll)="onAllStudentsDeSelected()" formControlName="studentsItems"> </ng-multiselect-dropdown> </form> </div>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Esto sucede porque la parte html del componente se carga pero los datos aún no provienen de la API, es decir, la suscripción aún no está completa.

Debe establecer una marca, decir isLoaded como true en una suscripción exitosa y actualizar el formulario también. En html, use una declaración ngIf para que el menú desplegable no se cargue sin los datos.

 <div *ngIf="isLoaded && showStudensMenu" class="form-group"> <form [formGroup]="studentsDropDownForm"> <!-- your code --> </form> </div>

En html, cambie formControlName="studentsItems " a "formControl]="form.controls['studentsItems'] si es necesario.

Suscripción:

 this.studentService.getStaffStudents(+loadedUserId).subscribe(async selectedStudents => { //your code this.isLoaded=true; //Update the Form this.studentsDropDownForm = this.fb.group({ studentsItems: [this.selectedStudents] }); } })

No olvide inicializar isLoaded como falso;

about 4 years ago · Juan Pablo Isaza Report

0

Pero la selección múltiple está consumiendo [data]="students" , ¿no debería enviar los nuevos elementos a students[] ? Si los valores seleccionados se leen de this.selectedStudents , puede activar la detección de cambios restableciendo los elementos usando spread ... p. ej. this.selectedStudents = [...this.selectedStudents] .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!