【发布时间】:2019-08-15 15:51:41
【问题描述】:
我正在调试使用 ng-select 的组件,每次我输入输入时,我的 ngModel 都会发生变化,即使我在视图中没有使用 ngModel。我已经删除了对 ngModel 的所有使用,只保留了类属性。
<div>
<div class="invlisible" #list>
<div *ngFor="let item of items">{{item}}</div>
</div>
<div class="invlisible" #value>{{ngModel}}</div>
<ng-select [items]="items"
[clearable]="false"
[loading]="loading"
[placeholder]="placeholder"
[typeahead]="typeahead">
</ng-select>
</div>
当我将“x”放入 ng-select 输入时,我的 ngModel 正在发生变化,我已经删除了对 ngModel 的所有使用,只有这在我的组件中:
@Component({
selector: 'disco-ng-select',
templateUrl: './disco-ng-select.component.html',
styleUrls: ['./disco-ng-select.component.scss']
})
export class DiscoNgSelectComponent extends CSSProps implements OnInit, OnDestroy {
private _value: any;
@Input() public items: any[];
@Input() public loading: boolean;
@Input() public placeholder: string;
@Input() public typeahead: Observable<any[]>;
@Input() public ngModel: any;
@Output() public ngModelChange = new EventEmitter<any>();
constructor(
_host: ElementRef) {
super(_host);
}
public onChange(value: any) {
this.ngModelChange.emit(value);
}
}
ngModel 没有以任何方式连接到我的组件,但它的值在我输入时正在改变。当我输入空输入并在该输入中输入文本时也会发生同样的情况,ngModel 正在改变。
如何使 ngModel(我想使用 ngModel 而不是 [model]="value")与普通的双向数据绑定一样工作?
【问题讨论】:
-
可以添加
NG_VALUE_ACCESSORprovider,实现ControlValueAccessor接口,如this answer所示。 -
@ConnorsFan 谢谢,这正是我所需要的,将相同的
NG_VALUE_ACCESSOR代码 + 接口和空方法禁用默认行为。如果你愿意,你可以添加答案,它会更容易找到。
标签: angular typescript data-binding