3

I have a component, that displays a list of items. On every item, there is a dropdown with which you can change a value. The only issue is, that when creating the component, the selected item in the dropdown is empty. It appears only if I click anywhere on the page.

Typescript

export class Component {

    @Input() files: ProductFile[];

    contentTypes: { [id: string]: string } = {};

    ngOnInit(): void {
        this.files.forEach(f => this.contentTypes[f._id] = f.contentType);
    }

    public fileTypes: string[] = [/* items in the dropdown */];

}

HTML

<div
    *ngFor="let f of files"
    class="file shadow"
>
    <dy-dropdown
        [items]="fileTypes"
        [ngModel]="contentTypes[f._id]"
        (ngModelChange)="onUpdate($event, f)"
    ></dy-dropdown>
</div>

P.S.: dy-dropdown is a custom Form Control which simply changes the value when the user selects an item in the dropdown list.

Florian Ludewig
  • 4,338
  • 11
  • 71
  • 137

2 Answers2

1

Try calling detection changes manually using ChangeDetectorRef

import { ChangeDetectorRef } from 'angular/core';

constructor(private chRef: ChangeDetectorRef){

}

and call inside your onUpdate function

this.chRef.detectChanges();
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

Might be, you need to trigger change detection manually.Here is the code.

import {ChangeDetectorRef} from '@angular/core';

constructor(private cdr: ChangeDetectorRef)

ngOnInit(): void {
  this.files.forEach(f => this.contentTypes[f._id] = f.contentType);
  this.cdr.detectChanges();
}
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27