Angular 5自定义指令输入属性值未定义

时间:2018-09-18 16:54:19

标签: angular angular5

我正在尝试将值传递给指令的自定义属性,但是当我尝试对其进行记录时,它说它是未定义的。

这是我的component.html:

<div appRadialMenu [step]="4"></div>

这是我的指令。

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

// jQuery
import * as $ from 'jquery';

@Directive({
  selector: '[appRadialMenu]'
})
export class RadialMenuDirective implements OnInit {
  @Input() step;

  constructor(private elRef: ElementRef) {
      $(elRef.nativeElement).click(function () {
          console.log(this.step);
      }
  }
  ngOnInit() {
      console.log(this.step);
  }
}

编辑:我也尝试使用

@Input('step') step;

编辑2 :谢谢大家,它起作用了,我做了以下更改:

我更改了click事件绑定,并将其移至ngOnInit,还更改了选择器

selector: 'appRadialMenu'
// ......
@Input('step') step;

constructor(private elRef: ElementRef) {}

ngOnInit() {
    $(this.elRef.nativeElement).click(() => {
        console.log(this.step);
    });
}

component.html:

<appRadialMenu [step]="4"></appRadialMenu>

2 个答案:

答案 0 :(得分:0)

您应该为input属性创建一个别名,这样就不必在指令中使用名为from(sql:select name, age from person?datasource=xyz).to(direct:foo); from(sql:select name, age from person?datasource=abc).to(direct:foo); from(direct:foo).to(stream:out); 的另一个属性。

除此之外,您还将在steps中获得更改后的steps计数。因此,请使用该名称代替ngOnChanges

这应该是您的指令。

ngOnInit

由于将使用带有属性绑定语法的import { Directive, ElementRef, Input, OnChanges } from '@angular/core'; @Directive({ selector: '[appRadialMenu]' }) export class RadialMenuDirective implements OnChanges { @Input('appRadialMenu') step; constructor(private elRef: ElementRef) { } ngOnChanges() { console.log('Got steps as: ', this.step); } } 指令,因此应为它分配一个将在Component类上定义的属性。

这是在组件模板中使用它的方法:

appRadialMenu

这里是Sample StackBlitz供您参考。

答案 1 :(得分:0)

您可以使用 @Input() 以多种方式将值传递给指令,即

  1. 您可以直接将一些值传递给 directive,即 [MyDirective]="someValue"
  2. 您可以在 directive 中创建另一个输入变量来接受另一个值,即 @Input('otherValue') otherValue: number

HTML

<div [MyDirective]="someValue" [otherValue]="20">
     {{someValue | number: '1.0-0'}}
</div>

指令

@Directive({
  selector: '[MyDirective]'
})
export class MyDirective implements OnChanges {

  @Input('MyDirective') value: number
  @Input('otherValue') otherValue: number
  constructor(private elRef: ElementRef) { }

  ngOnChanges() {
    console.log(this.value)
    console.log(this.otherValue)
  }
}

注意:您可以使用 @Input() 将任意数量的变量传递给指令。