我正在调试使用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>
当我将ngModel更改为ng-select输入时,我已经删除了对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"
)与普通的双向数据绑定相同?
答案 0 :(得分:0)
您可以使用Angular使用的特定语法来创建类似的行为,但是使用自定义名称。
它在起作用:https://stackblitz.com/edit/angular-ta6sic?file=src%2Fapp%2Fapp.component.html
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
_name: string;
@Input() get name() { return this._name; }
@Output() nameChange = new EventEmitter<string>();
set name(value) {
this._name = value;
this.nameChange.emit(this._name);
}
}
您必须
_name
)的私有属性Change
这样,您可以像这样使用组件:
<hello [(name)]="name"></hello>