繁体   English   中英

大写指令不更新输入角度

[英]uppercase directive not update input angular

如果我打印console.log()来查看格式化方法的值,那么我可以看到我输入的值,但是在inputText上文本不会更新为大写;

我对html的声明

<input type="text" uppercase >

import {Directive, Input, Output, EventEmitter, OnInit} from 'angular2/core';

@Directive({
    selector: '[uppercase]',
    host: {
        '[value]': 'uppercase',
        '(input)': 'format($event.target.value)'
    }
})
export class Uppercase implements OnInit {

    @Input() uppercase: string;
    @Output() uppercaseChange: EventEmitter<string> = new EventEmitter<string>();

    constructor() {
    }

    ngOnInit() {
        this.uppercase = this.uppercase || '';
        this.format(this.uppercase);
    }

    format(value) {
        value = value.toUpperCase();
        this.uppercaseChange.next(value);
    }
}

我该怎么写大写字母?

您可能需要像其他<input type="text" uppercase >一样更新模板,以应用Directive所有更改。

但是,更正逻辑很重要,因为uppercase指令将应用于输入nativeElement类的nativeElement

因此,您可能需要实现ControlValueAccessor接口并调整指令。

这是一个示例,您如何执行此操作(我修改了您的代码): stackblitz上的大写指令

我在代码中添加了一些注释。

让我知道您是否要存档。


编辑(查看下面的评论)

如果您正在寻找一种更简单的方法来创建指令并保留所需的两件事,则输入文本应为大写 字母占位符应为​​小写字母 ,您可以执行以下操作

uppercase.directive.ts

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

@Directive({
 selector: '[uppercase]'
})
export class UppercaseDirective {
  constructor(public ref: ElementRef) { }

  @HostListener('input', ['$event']) onInput(event) {
     this.ref.nativeElement.value = event.target.value.toUpperCase();
  }
}

your.template.html

<input placeholder="placeholder lowercase" uppercase type='text'>

我在这里关于stackblitz的另一个演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM