加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2 – 指令不更新模型

发布时间:2020-12-17 17:02:35 所属栏目:安全 来源:网络整理
导读:我有一个包含数字值的html输入框的指令.当用户将数字粘贴到文本框中时,我有一个“清理”数字的指令(剥离逗号,美元符号等).清洁代码似乎工作正常,但即使文本框显示清理后的值,我的模型也没有使用清理后的值更新. 如何使用新值更新模型? Plnkr here 这是一个
我有一个包含数字值的html输入框的指令.当用户将数字粘贴到文本框中时,我有一个“清理”数字的指令(剥离逗号,美元符号等).清洁代码似乎工作正常,但即使文本框显示清理后的值,我的模型也没有使用清理后的值更新.

如何使用新值更新模型?

Plnkr here

这是一个精简的例子:

app.ts

@Component(
@Component({
  selector : 'my-app',template : `
  <div>
    <br/>
    <br/>
    <p>Stack Overflow person - give focus to text box and then lose focus by clicking elsewhere in the screen. <br/>The model is not updated.</p>
    <br/>Model value: {{ balanceAmount }}
    <br/>
    <br/>
    <input type="text" [(ngModel)]="balanceAmount" myCurrencyFormatter  /><br/>
  </div>
  `,})
export class App {
  name:string;
  constructor(private mycurpipe: MyCurrencyPipe) {
    this.balanceAmount = 1234567.89;
  }
}

货币格式化,Directive.ts

@Directive({ selector: "[myCurrencyFormatter]" })
export class MyCurrencyFormatterDirective implements OnInit {

  private el: any;

  constructor(
    private elementRef: ElementRef,private currencyPipe: MyCurrencyPipe
  ) {
    this.el = this.elementRef.nativeElement;

  }

  ngOnInit() {
    this.el.value = this.currencyPipe.transform(this.el.value);
  }

  @HostListener("focus",["$event.target.value"])
  onFocus(value) {
    this.el.value = this.currencyPipe.parse(value); // opossite of transform
  }

  @HostListener("blur",["$event.target.value"])
  onBlur(value) {
    this.el.value = this.cleanNumber(value); //"987654" ;//this.currencyPipe.transform(value);
  }

  cleanNumber (value: number) {
    return 8888888; // clean logic goes here,removed for plunk example
  }


}

Plnkr here

解决方法

您需要为模型添加发射器.这是在Angular 2中实现双向绑定的方法.看看@Output()行ngModelChange = new EventEmitter();以及我如何使用此变量向调用者发出更改.

import { Directive,HostListener,ElementRef,OnInit,EventEmitter,Output } from "@angular/core";
import { MyCurrencyPipe } from "./my-currency.pipe";

@Directive({ selector: "[myCurrencyFormatter]" })
export class MyCurrencyFormatterDirective implements OnInit {

  private el: any;
  @Output() ngModelChange = new EventEmitter();

  constructor(
    private elementRef: ElementRef,["$event.target.value"])
  onFocus(value) {
    this.el.value = this.currencyPipe.parse(value); // oposite of transform
    this.ngModelChange.emit(this.el.value);
  }

  @HostListener("blur",["$event.target.value"])
  onBlur(value) {
    this.el.value = this.cleanNumber(value); //"987654" ;//this.currencyPipe.transform(value);
    this.ngModelChange.emit(this.el.value);
  }

  cleanNumber (value: number) {
    return 8888888;
  }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读