用字符串作为输入的angular2结构指令

angular2 structural directive with String as input

本文关键字:angular2 结构 指令 输入 字符串      更新时间:2023-09-26

我试图创建一个结构指令与给出的例子

只是修改传递字符串作为输入在这里,我得到了"未定义"作为输入值,而调用这个指令的形式标记。

@Input() set myUnless(value: String) {
    if (value=== 'something') {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

有什么帮助吗?

编辑:

我们的想法是创建一个hasRole指令,它接受一个角色作为字符串,并根据是否在本地存储的角色中找到这个值返回布尔值。

实现代码为:

 <a routerLink="/list" *unless="ADMIN">
          <i class="fa fa-list"></i> <span>List</span>
 </a>

指令的代码如下:

import { Directive, Input } from '@angular/core';
import { TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({ selector: '[unless]' })
export class Unless {
    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef
    ) { }
    @Input() set unless(role: String) {
        return localStorage.getItem('roles').indexOf(role) > -1;
    }
}

组件的属性ADMIN实际上是undefined;-)

使用相反

*unless="'ADMIN'"