我试图使用debounce
创建自定义输入组件,所以我遵循了this suggestion
Debounce
可以工作,但是一开始输入值未正确设置为输入组件。
这是我的实现方式:
app.component.ts
import { Component } from '@angular/core';
import { DebInputComponent } from './deb-input/deb-input.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
test:string ='test';
}
app.component.html
<deb-input [(ngModel)]="test" type="text" label="Test" ngDefaultControl>
</deb-input>
<div>{{test}}</div>
deb-input.component.ts
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { Component, Input } from '@angular/core';
@Component({
selector: 'deb-input',
templateUrl: './deb-input.component.html',
styleUrls: ['./deb-input.component.css'],
providers: []
})
export class DebInputComponent {
@Input() label: string;
@Input() type: string="text";
@Input() model: string;
modelChanged: Subject<string> = new Subject<string>();
constructor() {
this.modelChanged
.pipe(debounceTime(1000))
.pipe(distinctUntilChanged())
.subscribe(newValue => {this.model = newValue;
console.log(this.model)});
}
changed(text: string) {
this.modelChanged.next(text);
}
}
deb-input.component.html
<div>
<span>{{label}}</span>
<input [(ngModel)]='model' (ngModelChange)='changed($event)' [type]='type' ngDefaultControl/>
</div>
如何确保model
内的deb-input
已正确设置为“测试”?
答案 0 :(得分:2)
您使用的是ngmodel
,而您应该使用组件输入的名称
<deb-input [model]="test" type="text" label="Test" ngDefaultControl>
</deb-input>
如果要对组件进行双向绑定,只需将eventEmitter
添加到组件中,如下所示:
@Input() model: string;
@Output() modelChange = new EventEmitter<string>();
modelChanged: Subject<string> = new Subject<string>();
@Output() modelChangeEvt = new EventEmitter<string>();
constructor() {
this.modelChanged
.pipe(debounceTime(1000))
.pipe(distinctUntilChanged())
.subscribe(newValue => {this.model = newValue;
this.modelChangeEvt.emit(newValue);
console.log(this.model)});
}
然后在HTML中使用两种方式绑定:
<deb-input [(model)]="test" type="text" label="Test" ngDefaultControl></deb-input>