没有将值传递给angular7中的指令

时间:2019-06-11 08:41:35

标签: javascript angular typescript angular7 angular-directive

我在Angular7中创建了一个Directive,但是当我需要将一个string值从html传递给指令时。

但是当我在HTML中使用它时:

<ng-template [appValidatePermission]='CreateRole'>
   <router-outlet></router-outlet>
</ng-template>

这是我的指令:

    @Directive({
  selector: '[appValidatePermission]'
})
export class ValidatePermissionDirective implements OnInit {

  show: boolean;
  constructor(private templateRef: TemplateRef<any>,
              private viewContainerRef: ViewContainerRef
    ,         private dynamic: DynamicPermissionService) { }

  // tslint:disable-next-line:no-input-rename
  @Input() AccessName: string;

  ngOnInit() {
    this.ValidatePemission();
    if (this.show) {
      this.viewContainerRef.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainerRef.clear();
    }
  }
  ValidatePemission() {
    console.log('AccessName : ', this.AccessName);
    const find = this.dynamic.dynamicModel.find(x =>
      !! x.actionsVM.find(z => z.actionEnglishName === this.AccessName));
    if (find) {
        this.show = true;
      } else {
         this.show = false;
      }
  }
}

它告诉我AccessName: Undefined

问题出在什么地方???我该如何解决??

2 个答案:

答案 0 :(得分:1)

您可以尝试这样

<ng-template [AccessName]="<value you want to send>" appValidatePermission >
   <router-outlet></router-outlet>
</ng-template>

答案 1 :(得分:1)

您没有传递变量。 要使用指令,请在HTML中这样做

  <ng-template appValidatePermission AccessName="CreateRole">
   <router-outlet></router-outlet>
   </ng-template>

请注意,如果您使用[]并想输入搅拌声,则应该这样做

  <ng-template appValidatePermission [AccessName]="'CreateRole'">
   <router-outlet></router-outlet>
   </ng-template>