【发布时间】:2021-10-08 16:35:45
【问题描述】:
我正在使用 Angular Material 构建一个通用的选择器组件。手动设置值时,它可以正常工作,但是,如果我从打字稿更新表单值,则视图不会反映该更改。
selector.component.html
<mat-form-field appearance="standard">
<mat-label>{{ label }}</mat-label>
<mat-select
[formControl]="formControl"
(valueChange)="onChange($event)"
multiple
>
<mat-select-trigger>
{{ !!selectedData.length ? selectedData[0][elementLabel] : '' }}
<span *ngIf="selectedData.length > 1" class="additional-selection">
(+{{ selectedData.length - 1 }}
{{ selectedData?.length === 2 ? 'other' : 'others' }})
</span>
</mat-select-trigger>
<mat-option
*ngFor="let element of data; trackBy: trackByFunction"
[value]="element"
>{{ element[elementLabel] }}</mat-option
>
</mat-select>
</mat-form-field>
selector.component.ts
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
Output,
} from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'selector',
templateUrl: './selector.component.html',
styleUrls: ['./selector.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SelectorComponent {
@Input() data: any[] = [];
@Input() set init(value: any[]) {
this.selectedData = value;
}
@Input() label: string = '';
@Input() elementLabel: string = '';
@Output() onChangeEvent: EventEmitter<any[]> = new EventEmitter();
selectionDisplayText = '';
formControl = new FormControl([]);
get selectedData(): any[] {
return this.formControl.value;
}
set selectedData(data: any[]) {
this.formControl.setValue(data);
}
trackByFunction(item: any): string {
return item[this.elementLabel];
}
onChange = (data: any[]) => {
this.selectedData = data;
this.onChangeEvent.emit(this.selectedData);
};
}
当我尝试从父组件更新选择值时(使用init 输入),代码到达set selectedData 方法并且formControl 值设置为OK,但视图显示一个空选择。我错过了什么?
谢谢
【问题讨论】:
-
你正在使用 onPush。当你删除它时它会起作用吗?
-
不,不影响
-
我认为在 ngOnInit 函数中设置 init 的值会更好。对我来说,这听起来像是一个 changeDetection 问题。这有帮助吗? angular.io/api/core/OnInit
标签: angular angular-material form-control