我有一个显示项目列表的组件。在每个项目上都有一个下拉菜单,您可以使用该下拉菜单更改值。唯一的问题是,在创建组件时,下拉列表中的所选项目为空。 仅当我单击页面上的任意位置时,它才会出现。
打字稿
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
是一个自定义的窗体控件,当用户在下拉列表中选择一个项目时,它仅更改值。
答案 0 :(得分:1)
尝试使用 ChangeDetectorRef
import { ChangeDetectorRef } from 'angular/core';
constructor(private chRef: ChangeDetectorRef){
}
并在onUpdate函数中调用
this.chRef.detectChanges();
答案 1 :(得分:0)
可能是,您需要手动触发更改检测。这是代码。
import {ChangeDetectorRef} from '@angular/core';
constructor(private cdr: ChangeDetectorRef)
ngOnInit(): void {
this.files.forEach(f => this.contentTypes[f._id] = f.contentType);
this.cdr.detectChanges();
}