rez*_*esh 2 javascript angular2-forms angular angular-reactive-forms angular-event-emitter
考虑带有输入的 Angular 反应形式。每当输入发生变化时,我们都希望保留其旧值并将其显示在某个地方。下面的代码按照显示的方式执行此操作:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Reactive Form';
changedValue;
oldValue;
ooldValue;
rform = new FormGroup({
inputOne: new FormControl('chang me')
});
onOneChange(event) {
this.changedValue = event.target.value;
console.log('oneChanged', this.changedValue, 'old value is', this.oldValue);
this.ooldValue = this.oldValue;
setTimeout( ()=>this.oldValue = this.changedValue, 1);
}
}Run Code Online (Sandbox Code Playgroud)
<form [formGroup]="rform">
<label>
One:
<input formControlName="inputOne" (change)="onOneChange($event)"/>
</label>
</form>
<p>
changed value: {{changedValue}}
</p>
<p>
old value: {{ooldValue}}
</p>Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它已通过在代码中保留三个变量来解决,这是不可取的(是的,changedValue可以删除该变量,但仍然有两个变量保留旧值很烦人,不是吗?)。
有没有办法用更少的变量重写代码?Angular 本身有下降的方式来做到这一点吗?
您可以在这里找到代码
小智 6
valueChanges 是一个 Observable,因此您可以成对通过管道来获取订阅中的上一个和下一个值。
// No initial value. Will emit only after second character entered
this.form.get('inputOne')
.valueChanges
.pipe(pairwise())
.subscribe(([prev, next]: [any, any]) => ... );
// Fill buffer with initial value, and it will emit immediately on value change
this.form.get('inputOne')
.valueChanges
.pipe(startWith(null), pairwise())
.subscribe(([prev, next]: [any, any]) => ... );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7615 次 |
| 最近记录: |