我有一个formControl,我试图设置它的值,然后触发变化检测,这样其他组件中的valueChanges
就可以得到我在这里设置的变化-但它不起作用。true。不触发valueChanges
<mat-select [formControl]="myCtrl" (selectionChange)="changed($event.value)">
<mat-option ... >{{ ... }}</mat-option>
</mat-select>
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MyComponent),
multi: true,
},
],
...
public selectedValue: number;
public changed: (value: number) => void;
public touched: () => void;
public isDisabled: boolean;
writeValue(value: any): void {
this.selectedValue = value;
}
registerOnChange(fn: any): void {
this.changed = fn;
}
registerOnTouched(fn: any): void {
this.touched = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.isDisabled = isDisabled;
...
myCtrl = = new FormControl();
...
ngOnInit(): void {
this.subject$.subscribe((data) => {
this.data = data
if (data) {
//this line below doesn't seem to kick off change detection
this.myCtrl.setValue(1, { emitEvent: true })
/*I also tried forcing change detection with the this.changed method but got an
error like ERROR TypeError: this.changed is not a function*/
//this.changed(1)
}
}
)
}
1条答案
按热度按时间kzipqqlq1#
我猜你没有得到它的权利。你只需要做一个函数和
selectionChange()
调用。像在你的情况下,做一个名为changed
的函数。尝试控制整个事件,并检查是否值显示在对象中,如果它这样做。你可以使用该值在任何地方,你需要。即传递到一个变量或观察者