代码之家  ›  专栏  ›  技术社区  ›  Stepan Suvorov bolelamx

是否有一种简单的方法覆盖基指令?

  •  5
  • Stepan Suvorov bolelamx  · 技术社区  · 7 年前

    我正在寻找一种简单的方法来覆盖开箱即用的指令的行为,例如 ngIf

    因此,我可以做一个儿童指令,并延长行为后,声明为母语之一。

    备注:我知道重写标准功能是非常糟糕的做法,但我这么做只是为了学习/研究。

    3 回复  |  直到 7 年前
        1
  •  2
  •   Sachin Gupta    7 年前

    您只需将选择器定义为现有指令之一。看看我在stackblitz上的例子。

    https://stackblitz.com/edit/angular-overload-builtin-directive

        2
  •  0
  •   Derviş Kayımbaşıoğlu    7 年前

    你可以考虑像myif一样写你自己的ngif

    import { Directive, Input, ElementRef, TemplateRef, ViewContainerRef } from '@angular/core';
    
    @Directive({
      selector: '[myIf]'
    })
    export class MyIfDirective {
    
      constructor(
        private element: ElementRef,
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef
      ) {
      }
    
      @Input()
      set myIf(val) {
        if(val) {
          this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
          this.viewContainer.clear();
        }
      }
    }
    

    然后

    <div *myIf="isVisible">
        Hi there!
    </div>
    

    否则这会有帮助

    import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
    import {NgIf} from "@angular/common"
    
    @Directive({
      selector: '[ngIf][myNgIf]'
    })
    export class myNgIf extends NgIf {
    
      @Input() myNgIf: boolean;
    
      constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef) {
    
        super(viewContainer, templateRef);
      }
    
    
      @Input()
      set ngIf(val) {
        if (val) {
          ...
        } else {
          this.viewContainer.clear();
        }
      }
    
        3
  •  0
  •   Vojtech    7 年前

    如果您的目标是扩展已经提供的行为,那么很容易做到这一点。您只需要创建自定义指令并使用选择器 [ngIf]

    但是您在其上使用指令的元素仍然与原始的 ngIf . 所以你不会得到一个好的、干净的解决方案来摆脱最初的行为。 你可以看到一个例子 stackblitz


    要真正重写,这些解决方案可能会以某种方式可用,而不是黑客

    1. 自行重新实现/扩展指令,并将其导入到模块中而不是原始模块中

      • 万一 NGIF 那就意味着创造习惯 CommonModule 从角核暴露出这个指令
    2. 使用角度调整叉

    3. 使用regex查找所需指令的所有匹配项(例如 NGIF 并用一些自定义名称替换它,您可以在选择器中轻松使用它。 [myNgIf] )