Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda