首页 > 解决方案 > 有没有一种简单的方法来覆盖基本指令?

问题描述

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

所以我可以制作一个子指令并扩展行为,然后声明为原生指令。

PS:我知道覆盖标准功能是非常糟糕的做法,但我这样做只是为了学习/研究目的。

标签: angularangular-directive

解决方案


你可以考虑写你自己的 ngIf 像 myIf

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();
    }
  }

推荐阅读