有没有简单的方法可以覆盖基本指令?

时间:2018-12-28 09:15:58

标签: angular angular-directive

我正在寻找一种简单的方法来覆盖现成的指令的行为,例如ngIf

所以我可以创建一个子指令并扩展其行为,然后在声明为本地指令后进行扩展。

P.S .:我知道重写标准功能是非常糟糕的做法,但我这样做只是出于学习/研究目的。

3 个答案:

答案 0 :(得分:2)

您可以简单地将选择器定义为现有指令之一。在stackblitz上查看我的示例。

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

答案 1 :(得分:0)

您可以考虑像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();
    }
  }

答案 2 :(得分:0)

如果您打算扩展已经提供的行为,则可以很容易地做到这一点。您只需要创建自定义指令并使用选择器即可,例如[ngIf]

但是您在其上使用了伪指令的元素仍然与原始ngIf相关联。因此,您将无法摆脱原来的行为,而是一个不错的解决方案。 您可以在stackblitz

上看到一个示例

要真正覆盖这些问题,可以使用这些解决方案,而不是破解

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

    • ngIf的情况下,这意味着创建自定义CommonModule,该自定义{@ 1}}从角核暴露了该指令
  2. 使用角度的“调整”叉

  3. 使用正则表达式查找所有出现的所需指令(例如ngIf)并将其替换为一些自定义名称,您可以在选择器([myNgIf])中轻松使用该自定义名称

相关问题