【问题标题】:Directive not working on Ionic 3.19 + Angular 4.1.3指令不适用于 Ionic 3.19 + Angular 4.1.3
【发布时间】:2017-12-11 17:41:33
【问题描述】:

我正在尝试创建一个指令,以便在用户键入时将输入字符转换为大写,但我开始相信这是不可能的。

我有什么: 大写.directive.ts:

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

@Directive({
  selector: '[UpperCaseInput]',
  host: {
    '[value]': 'UpperCaseInput',
    '(input)': 'format($event.target.value)'
  }
})
export class UppercaseInput 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);
  }
}

大写.directive.module.ts:

import {
  NgModule
} from '@angular/core';
import {
  UppercaseInput
} from './uppercase.directive';

@NgModule({
  declarations: [UppercaseInput],
  imports: [],
  exports: [UppercaseInput]
})
export class UppercaseInputModule {}

然后我在我的 app.import.ts 中导入模块:

import {
  UppercaseInputModule
} from '../directives/uppercase.directive.module';
...
export const MODULES = [UppercaseInputModule];

在我的 app.module.ts 中:

@NgModule({
  bootstrap: [IonicApp],
  declarations: [
    ...
  ],
  imports: [
    ...,
    MODULES,
    SharedModule
  ],
  ...
})

当我尝试这样的事情时:

<input type="text" class="form-control" ([UpperCaseInput])='user.name' placeholder="Your name here" />

我得到: 错误:模板解析错误: 无法绑定到“大写输入”,因为它不是“输入”的已知属性。

那么,我在这里做错了什么?我错过了什么?

【问题讨论】:

    标签: angularjs ionic3


    【解决方案1】:

    试试这个方法:

    import { Directive, AfterViewInit, HostListener, ElementRef } from '@angular/core';
    
    @Directive({
      selector: 'ion-input[UpperCaseInput]'
    })
    export class UppercaseInput implements AfterViewInit {
    
      constructor(public element: ElementRef) { }
    
      ngAfterViewInit(): void {
        this.applyUppercase();
      }
    
      @HostListener('keyup', ['$event.target'])
      onkeyup(input: HTMLTextAreaElement): void {
        this.applyUppercase();
      }
    
      applyUppercase(): void {
        let input = this.element.nativeElement.querySelector('input');
    
        if (input) {
          input.value = input.value.toUpperCase();
        }
      }
    }
    

    并且在 html 中你改变了 input 标签

    <ion-input type="text" class="form-control" placeholder="Your name here" UpperCaseInput></ion-input>
    

    希望对你有帮助。

    【讨论】:

    • 是的,它工作了,但主要问题是我在哪里导入了指令模块,现在都设置好了,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2015-04-23
    相关资源
    最近更新 更多