"修剪"角度2的指令并反映对ngModel

时间:2017-04-13 08:55:25

标签: angular angular-directive angular2-ngmodel

我想创建Angular 2指令,该指令只会从用户输入到输入字段的文本的开头和结尾处确定空格。

我有输入字段

<input trim name="fruit" [(ngModel)]="fruit"/>

和指令

import {Directive, ElementRef} from "@angular/core";

@Directive({
  selector: 'input[trim]',
  host: {'(blur)': 'onChange($event)'}
})

export class TrimWhiteSpace {

  constructor(private cdRef:ChangeDetectorRef, private el: ElementRef){}

  onChange($event:any) {
    let theEvent = $event || window.event;
    theEvent.target.value = theEvent.target.value.trim();
  }
}

工作正常,删除空格并更改输入字段中的文本,但问题是ngModel变量中的值&#34; fruit&#34;没有改变,它仍然包含在开头或结尾有空格的文本。

我还尝试将以下内容添加到onChange方法

this.el.nativeElement.value = theEvent.trim();
this.cdRef.detectChanges();

并将表单(模糊)更改为(ngModelChange),但ngModel中的文本不受影响。

有什么建议吗?

7 个答案:

答案 0 :(得分:7)

避免混淆更改模型属性名称。

<input name="fruit" [(ngModel)]="fruit1" (change)="fruit1=fruit1.trim()"/>

答案 1 :(得分:4)

你看过https://github.com/anein/angular2-trim-directive吗?

似乎它会解决您的用例

答案 2 :(得分:0)

@ErVipinSharma我改变了文件src / input-trim.directive.ts,您可以在上面链接中找到github。在这个文件中我删除了方法

        <s:form name="search_Details" id="search_Details">    

    <div class="form-group">
        <label class="col-sim-4 control-label"><s:text name="Name" /></label>
        <div class="col-sim-6">
           <input type="text" id="Name" placeholder="Name" name="Name" class="form-control"  size="17"  >
        </div>
    </div>

</s:form>

并添加了方法

@HostListener( 'input', ['$event.type', '$event.target.value'] )
onInput( event: string, value: string ): void {
    this.updateValue( event, value );
}

答案 3 :(得分:0)

虽然已经晚了一年多,但是您可能要尝试https://www.npmjs.com/package/ngx-trim-directive

这是基于一个简单的事实,即Angular会监听输入事件以使视图到模型的绑定成为现实。

演示:https://angular-86w6nm.stackblitz.io,编辑者:https://stackblitz.com/edit/angular-86w6nm

答案 4 :(得分:0)

最好使用fromEvent来防止冗余更改检测(将由@HostListener执行)。示例中的CommonController只是基类,它触发onDestroy挂钩中的主题取消可观察的订阅。

# Do not create instance every time
scaler = StandardScaler()

def find_anomaly(trx1,outliers_fraction):    
    np_scaled = scaler.fit_transform(trx1)
    data = pd.DataFrame(np_scaled)
    # train isolation forest
    model =  IsolationForest(contamination=outliers_fraction, n_jobs=-1)
    model.fit(data) 
    trx1['anomaly'] = pd.Series(model.predict(data))
    return(trx1)

# not loop but apply
list_terminal_trx = trx.apply(lambda x: find_anomaly(x,outliers_fraction), axis =1).values

您可以创建通用的修整指令,该指令不仅会针对模糊事件进行修整,还会针对您将提供的任何内容进行修整:

@Directive({
  selector: '[appTrimOnBlur]'
})
export class TrimOnBlurDirective extends CommonController implements OnInit {

  constructor(private elementRef: ElementRef,
              @Self() private ngControl: NgControl) {
    super();
  }

  ngOnInit(): void {
    fromEvent(this.elementRef.nativeElement, 'blur').pipe(
      takeUntil(this.unsubscribeOnDestroy)
    ).subscribe(() => {
      const currentValue: string = this.ngControl.value.toString();
      const whitespace: string = ' ';
      if (currentValue.startsWith(whitespace) || currentValue.endsWith(whitespace)) {
        this.ngControl.control.patchValue(currentValue.trim());
      }
    });
  }

}

答案 5 :(得分:0)

以下指令可与Reactive-Forms一起使用以修剪所有表单字段:

@Directive({
  selector: '[formControl], [formControlName]',
})
export class TrimFormFieldsDirective {
  @Input() type: string;

  constructor(@Optional() private formControlDir: FormControlDirective, 
              @Optional() private formControlName: FormControlName) {}

  @HostListener('blur')
  @HostListener('keydown.enter')
  trimValue() {
    const control = this.formControlDir?.control || this.formControlName?.control;
    if (typeof control.value === 'string' && this.type !== 'password') {
      control.setValue(control.value.trim());
    }
  }
}

答案 6 :(得分:0)

我真的很喜欢这个指令,因为它几乎自动适用于所有内容:

import { Directive, forwardRef, HostListener } from '@angular/core';
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
const TRIM_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => TrimValueAccessorDirective),
  multi: true,
};
/**
 * The trim accessor for writing trimmed value and listening to changes that is
 * used by the {@link NgModel}, {@link FormControlDirective}, and
 * {@link FormControlName} directives.
 */
@Directive({
  // eslint-disable-next-line @angular-eslint/directive-selector
  selector: `
 input:not([type=checkbox]):not([type=radio]):not([type=password]):not([readonly]):not(.ng-trim-ignore)[formControlName],
 input:not([type=checkbox]):not([type=radio]):not([type=password]):not([readonly]):not(.ng-trim-ignore)[formControl],
 input:not([type=checkbox]):not([type=radio]):not([type=password]):not([readonly]):not(.ng-trim-ignore)[ngModel],
 textarea:not([readonly]):not(.ng-trim-ignore)[formControlName],
 textarea:not([readonly]):not(.ng-trim-ignore)[formControl],
 textarea:not([readonly]):not(.ng-trim-ignore)[ngModel],
 :not([readonly]):not(.ng-trim-ignore)[ngDefaultControl]'
 `,
  providers: [TRIM_VALUE_ACCESSOR],
})
export class TrimValueAccessorDirective extends DefaultValueAccessor {
  @HostListener('input', ['$event.target.value'])
  ngOnChange = (val: string) => {
    this.onChange(val.trim());
  };
  @HostListener('blur', ['$event.target.value'])
  applyTrim(val: string) {
    this.writeValue(val.trim());
  }
  writeValue(value: any): void {
    if (typeof value === 'string') {
      value = value.trim();
    }
    super.writeValue(value);
  }
}

从这里:https://medium.com/@rm.dev/angular-auto-trim-your-input-string-using-angular-directive-5ae72b8cee9d