【问题标题】:Angular 2: Attribute Directive not receiving Input ValuesAngular 2:属性指令未接收输入值
【发布时间】:2023-03-27 05:49:01
【问题描述】:

我制作了一个 heatMap Attribute 指令,它在调用时没有接收到值。

热图指令:

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

@Directive({
    selector: '[HeatMap]',
})

export class HeatMapDirective{

    @Input('startVal') public startVal: string;

    constructor(private el: ElementRef, private renderer: Renderer) {
        this.processHeatMap();
    }

    processHeatMap() {
     console.log(this.startVal); // prints undefined.
    }
}

HTML 元素:

    <td class="pad-10" [startVal]="'25'" HeatMap> 25 </td>

我有一个场景,我需要同时传递字符串和数值,但两者都不起作用。我错过了什么吗?

【问题讨论】:

  • 你有什么错误吗?
  • 没有错误! console.log(this.startVal); // prints undefined.
  • 检查 angular2 生命周期钩子。构造函数中没有初始化的@Input 值

标签: angular angular2-directives


【解决方案1】:

将您的 html 更改为:

<td class="pad-10" [startVal]="'25'" HeatMap> 25 </td>

【讨论】:

  • 我在这里添加时错过了它,它存在于实际实现中
  • 检查 'ngOnInit' 函数中的值,例如:ngOnInit() { console.log(this.startVal); }
【解决方案2】:

当从构造函数寻址它们时,输入值尚未初始化,像这样从 ngOnInit() 寻址它们:

ngOnInit() {
  this.processHeatMap();
}

【讨论】:

    猜你喜欢
    • 2016-06-29
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2017-02-14
    • 2016-10-02
    • 2017-04-02
    相关资源
    最近更新 更多