Angular的结构型指令

自定义一个结构型指令 * appUnless,当传入的值为false时显示,为true时隐藏。和ngIf的作用相反
unless.directive.ts

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

export class UnlessContext<T = unknown> {
  public $implicit: T = null!;
  public appUnless: T = null!;
  public attr: T = null!;
}

@Directive({
  selector: '[appUnless]'
})
export class UnlessDirective {

  private hasView:boolean = false;
  private context = new UnlessContext();

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainerRef: ViewContainerRef
  ) { }

  @Input()
  set appUnless(condition: boolean) {
    this.context.$implicit = this.context.appUnless = condition;
    this.context.attr = "123";
    if (!condition && !this.hasView) {
      /*使用这种方式只能在结构型指令用let的方式设置变量*/
      // this.viewContainerRef.createEmbeddedView(this.templateRef,{$implicit:condition, attr: "abc"});
      /*使用这种方式可以在结构型指令中同时使用let或者as设置变量*/
      this.viewContainerRef.createEmbeddedView(this.templateRef, this.context);
      this.hasView = true;
    } else {
      this.viewContainerRef.clear();
      this.hasView = false;
    }
  }

}

app.component.html
unless在app.component.ts中默认为false

*ngIf和*ngFor以及*appUnless都是一种语法糖,实际代码是被包裹在ng-template中的。
<p *appUnless="unless as un; let s;let a=attr; attr as test" [style]="{'backgroundColor':'lightgreen'}">A)自定义结构性指令 --s{{s}} --cc{{a}} --un{{un}} --test{{test}}
</p>

<ng-template [appUnless]="unless" let-un="appUnless" let-s let-a="attr" let-test="attr">
  <p [style]="{'backgroundColor':'#dedede'}">A)自定义结构性指令 --s{{s}} --cc{{a}} --un{{un}} --test{{test}}
  </p>
</ng-template>

页面显示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值