Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

281
Vistas
Unable to add defaults items to angular dropdown

i'm trying to display some default selected data to my angular dropdown menu but for some reason if i push() the items from inside the subscribe() method the items does not being selected and if i try adding the items outside of this specific subscribe method it adds the items to the dropdown without any problems.

NOTE: If i log my array, it gives me all the items, including the items that i added from inside the subscribe()

Part of my component:

    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"})

Part of my service:

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

My dropdown settings and FormGroup:

this.studentsDropDownSettings = {
    idField: 'student_id',
    textField: 'student_name',
    allowSearchFilter: true,
    noDataAvailablePlaceholderText: "No Available Students"
}

this.studentsDropDownForm = this.fb.group({
    studentsItems: [this.selectedStudents]
});

And my HTML element:

<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 Respuestas
Responde la pregunta

0

This happens because the html part of the component loads but the data hasn't come from the api yet i.e. subscription is not yet complete.

You need to set a flag, say isLoaded as true on successful subscription and update the form as well. In html, use a ngIf statement so that the dropdown does not load without the data.

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

In html, change formControlName="studentsItems" to "formControl]="form.controls['studentsItems'] if required.

Subscription:

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

    })

Don't forget to initialize isLoaded as false;

about 4 years ago · Juan Pablo Isaza Denunciar

0

But the multiselect is consuming [data]="students" shouldn't you push the new items to students[]? If the selected values are indeed read from this.selectedStudents you could trigger change detection by resetting the items using spread ... e.g this.selectedStudents = [...this.selectedStudents].

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda