代码之家  ›  专栏  ›  技术社区  ›  Davi Resio

大写指令不更新输入

  •  0
  • Davi Resio  · 技术社区  · 7 年前

    此大写指令不适用于。。。。 如果我打印console.log()以查看format方法上的值,我可以看到输入的值,但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);
        }
    }
    

    我怎样才能把文字改成大写?

    1 回复  |  直到 7 年前
        1
  •  1
  •   billyjov    7 年前

    你可能需要像这样更新你的模板 <input type="text" uppercase > 在其他情况下,应用 Directive .

    但是纠正你的逻辑很重要因为 uppercase 指令将应用于 nativeElement

    因此,您可能需要实现 控制值存取器

    下面是一个如何做到这一点的示例(我已经修改了您的代码): Uppercase directive on stackblitz

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

    如果这就是你想归档的,告诉我。


    输入文本应为大写 占位符应为小写 ,您可以简单地执行以下操作

    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();
      }
    }
    

    你的.template.html

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

    我做的 here

    推荐文章