【问题标题】:Angular2 Directive not reading given valueAngular2指令未读取给定值
【发布时间】:2017-06-10 20:30:57
【问题描述】:

我需要一个指令,它将动态值绑定到元素的 classList

指令

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

@Directive({
  selector: "[entityType]"
})
export class EntityTypeDirective {
  @Input() entityType: string;

  constructor(el: ElementRef) { 
    var labelClass = {
      C: "label-warning",
      F: "label-info",
      S: "label-success"
    };
    el.nativeElement.classList = `label ${labelClass[this.entityType]}`;
  }
}

标记

<span [entityType]="item.type">...<span>

问题

该指令绑定class="label undefined",因为entityTypeundefineditem.type 是来自 *ngFor 转发器的值,我想将其传递给指令。

我哪里出错了?

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    您在应该使用ngOnInit lifecycle hook 的地方出错了:)。这是 @Input 绑定完成的地方

    @Directive({
      selector: "[entityType]"
    })
    export class EntityTypeDirective implements OnInit {
      @Input() entityType: string;
    
      constructor(private el: ElementRef) {}
    
      ngOnInit() {
        let labelClass: any = {
          C: "label-warning",
          F: "label-info",
          S: "label-success"
        };
        this.el.nativeElement.classList = `label ${labelClass[this.entityType]}`;
      }
    }
    

    【讨论】:

      【解决方案2】:

      输入绑定在构造函数中不可用,请改用ngOnInit

      https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-12
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 2017-09-24
        • 2016-10-15
        • 2017-05-05
        • 1970-01-01
        相关资源
        最近更新 更多