angular - 如何将输入数据值发送到 angular-2 中的自定义指令?

标签 angular angular2-directives

我正在试验 angular-2 basic 的自定义指令,我想在自定义指令中解析输入值。

让我们看看。

我有一个名为 app.component.ts 的应用程序组件。我在哪里输入了一个输入字段。

<input [(ngModel)] = "myInput"/> 

接下来我构建一个自定义指令名称 custom.directive.ts

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

@Directive ({
  selector : '[customDir]'
})
export class CustomDirective{
  constructor(private el : ElementRef, private renderer: Renderer){ }
}

现在我想在“app.component.ts 中输入任何内容并在我的自定义指令中解析它,通过它我可以简单地在控制台中打印它..

让我们重新修改我的代码...

<app.component.ts>
<input [(ngModel)] = "myInput" [customDir] = "myInput"/> 
<custom.directive.ts>
import { Directive, ElementRef, Renderer, Input} from '@angular/core';

@Directive ({
  selector : '[customDir]'
})

export class CustomDirective{
  @Input('customDir') myInput : any;
  constructor(private el : ElementRef, private renderer: Renderer){ }
     console.log(this.myInput);
  }

但是它不能正常工作。打印未定义..

我担心的是...

1...我如何根据每次按键解析数据......?

请给我推荐任何人...

最佳答案

@Directive ({
  selector : '[customDir]',
  exportAs: 'customDir' // <<<=== added
})
export class CustomDirective{
  myInput : any;
}

像这样使用它

<input customDir #customDir="customDir" [(ngModel)]="myInputInApp" (ngModelChange)="customDir.myInput = $event"/> 

第一个 customDir 是为了让指令得到应用。

#customDir="customDir" 是创建一个引用指令的模板变量(需要exportAs)

[(ngModel)]="customDir.myInput" 绑定(bind)到模板变量 #customDir 及其属性 input 引用的指令. @Input() 在这种情况下不是必需的,因为这里使用的不是 Angular 绑定(bind)。

Plunker example

这应该也能工作并且更容易使用:

@Directive ({
  selector : '[customDir]',
})
export class CustomDirective{

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    console.log(event);
  }
}
<input customDir [(ngModel)]="someOtherProp"/> 

Plunker example

关于angular - 如何将输入数据值发送到 angular-2 中的自定义指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40417633/

相关文章:

javascript - 如何将基于 IIFE 的 JavaScript 模块导入 Angular TypeScript 应用程序?

javascript - 如何在 Angular 6 项目中添加 Bootstrap ?

Angular 2 : How can I apply directives to sanitized html/innerhtml

Angular 2 RC 2 使用移动手势(滑动、捏合、旋转)

Angular 2 输入指令修改表单控件值

angular - Angular2 中的 Lodash,声明 var_ :any not working

node.js - protractor-jasmine2-screenshot-reporter 未在所需文件夹中生成屏幕截图

Angular/RXJS - 跟踪陷入重试模式的 HTTP 请求

javascript - Ionic2:当你来到页面时,你如何选择要关注的输入?

angular - 多个 ngx 分页错误 Angular 2