Pass parameter to Angular 4 directive on input

筅森魡賤 提交于 2020-06-24 22:20:49

问题


I have an input text field like this

<input type="text" class="form-control"  [inputTextFilter]="A" [ngModel]="name">

and my directive is:

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

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

export class InputTextFilterDirective {
  @Input('inputTextFilter') params: string;

  @HostListener('keypress', ['$event'])
  onKeyUp(event: KeyboardEvent) {
    console.log('got parameters: '+this.params);
  }
}

and I have created a Directive called "inputTextFilter" to which I want to pass the "A" parameter. My passed parameter always shows as undefined.


回答1:


Try this.

Update:

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

@Directive({
  selector: '[inputTextFilter]'
})
export class MyDirective {
  @Input('inputTextFilter') params: string;
  constructor(){}
  ngOnInit(){
     console.log(this.params)
  }
}



回答2:


Try like this in directive :

import {Directive, Input, ElementRef} from 'angular2/core';
@Directive({
    selector: '[inputTextFilter]'
})
class FocusDirective {
    @Input() inputTextFilter: any;
    protected ngOnChanges() {
         console.log('inputTextFilter', this.inputTextFilter);
    }
}



回答3:


In the hope that this helps someone else...the problem is in the template.

When I pass the input as [myDirective]="A" the A is being intpreted as an undefined variable. Since I wanted to pass the letter A I should have said [myDirective]="'A'"



来源:https://stackoverflow.com/questions/46302684/pass-parameter-to-angular-4-directive-on-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!