首页 > 解决方案 > 大写指令不更新输入角度

问题描述

这个大写指令不适用于 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);
    }
}

我如何才能将文本大写?

标签: angular

解决方案


您可能需要像这样更新您的模板<input type="text" uppercase >,以应用您的Directive.

但纠正你的逻辑很重要,因为uppercase指令将应用于nativeElement类似的输入。

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

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

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

让我知道这是否是您想要归档的内容。


编辑(看下面的评论)

如果您寻找一种更简单的方法来创建指令并保留您需要的两件事 输入文本应该是大写并且占位符应该是小写,您可以简单地执行以下操作

大写的.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();
  }
}

你的.template.html

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

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


推荐阅读