首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >角2+与脱附

角2+与脱附
EN

Stack Overflow用户
提问于 2015-08-17 13:09:01
回答 15查看 256.2K关注 0票数 203

在AngularJS中,我能够通过使用ng模型选项来破除模型。

代码语言:javascript
运行
复制
ng-model-options="{ debounce: 1000 }"

我怎样才能从角度上揭穿模型呢?

我试着在文档里搜索,但什么也找不到。

https://angular.io/search/#stq=debounce&stp=1

一个解决方案是编写我自己的退出函数,例如:

代码语言:javascript
运行
复制
import {Component, Template, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'my-app'
})
@Template({
  url: 'app.html'
})
// Component controller
class MyAppComponent {
  constructor() {
    this.firstName = 'Name';
  }
    
  changed($event, el){
    console.log("changes", this.name, el.value);
    this.name = el.value;
  }

  firstNameChanged($event, first){
    if (this.timeoutId) window.clearTimeout(this.timeoutID);
    this.timeoutID = window.setTimeout(() => {
        this.firstName = first.value;
    }, 250)
  }
    
}
bootstrap(MyAppComponent);

和我的html

代码语言:javascript
运行
复制
<input type=text [value]="firstName" #first (keyup)="firstNameChanged($event, first)">

但是我在找一个内置的函数,有角的吗?

EN

Stack Overflow用户

发布于 2016-11-24 03:32:20

如果您不想处理@angular/forms,可以只使用带有更改绑定的RxJS Subject

view.component.html

代码语言:javascript
运行
复制
<input [ngModel]='model' (ngModelChange)='changed($event)' />

view.component.ts

代码语言:javascript
运行
复制
import { Subject } from 'rxjs';
import { Component }   from '@angular/core';
import 'rxjs/add/operator/debounceTime';

export class ViewComponent {
    model: string;
    modelChanged: Subject<string> = new Subject<string>();

    constructor() {
        this.modelChanged
            .debounceTime(300) // wait 300ms after the last event before emitting last event
            .distinctUntilChanged() // only emit if value is different from previous value
            .subscribe(model => this.model = model);
    }

    changed(text: string) {
        this.modelChanged.next(text);
    }
}

这确实会触发更改检测。要获得一种不会触发更改检测的方法,请查看Mark的答案。

更新

rxjs 6需要.pipe(debounceTime(300), distinctUntilChanged())

示例:

代码语言:javascript
运行
复制
   constructor() {
        this.modelChanged.pipe(
            debounceTime(300), 
            distinctUntilChanged())
            .subscribe(model => this.model = model);
    }
票数 195
EN
查看全部 15 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32051273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档