如何创建在Angular中删除其他指令之前将其删除的指令

我正在尝试制定一条指令,以防止触发另一条指令。我试图同时使用结构性指令和非结构性指令来完成此操作,但它们都没有起作用。

我正在使用的简单html:

<p appRemover appColor>
  Start editing to see some magic happen :)
</p>

比方说,我有一个颜色指令,只是更改了应用于红色的元素的颜色属性。这是color指令的代码:

constructor(private el: ElementRef) {}

  ngAfterViewInit(): void {
    this.el.nativeElement.style.color = 'red'
  }

我将制定另一个指令,即卸妆指令,该指令将执行以下操作:

constructor(private el: ElementRef,private ren: Renderer2) { }

  ngAfterViewInit(): void {
    this.ren.removeAttribute(this.el.nativeElement,'appColor');
  }

这里的想法是,我可以在呈现指令之前将指令从元素中删除。在移除appColor属性后打印el.nativeElement之后,该属性似乎消失了,但是颜色已经更改为红色。理想情况下,remover指令会在color指令之前触发,但我似乎无法找出Angular如何选择顺序。

我什至尝试使用结构指令来解决此问题:

constructor(private vc: ViewContainerRef,private template: TemplateRef<any>,private ren: Renderer2) { }

  ngOnInit() {
    this.ren.removeAttribute(this.template.elementRef.nativeElement,'appColor');
    this.vc.createEmbeddedView(this.template);
  }

但是实际上抛出一个错误,说el.removeAttribute不是函数吗?

是否存在用于使用指令删除或停止在同一元素上触发的另一指令的已建立模式?如果没有,是否有任何实际方法?

zhaohevip 回答:如何创建在Angular中删除其他指令之前将其删除的指令

在Angular中,无论如何(Github Issue)都不能动态创建/删除指令。如果它是导入的库,则需要将其派生并在该指令中添加例如@Input() disabled,因此当它处于活动状态时,它不会触发事件(当然,您也需要执行此逻辑)。

,

据我所知,您不能有条件地删除指令。您可以做的是,使元素具有两个版本,一个带有指令,一个不带有指令,然后使用*ngIf... else选择适当的元素。为避免重复元素的内部内容,请在通用模板中声明该内容,然后将其插入ngTemplateOutlet

<!-- Container element with the appColor directive -->
<p *ngIf="useColorDirective; else noColorDirective" appColor>
  <ng-container *ngTemplateOutlet="content"></ng-container>
</p>

<!-- Alternate container element,without the directive -->
<ng-template #noColorDirective>
  <p><ng-container *ngTemplateOutlet="content"></ng-container></p>
</ng-template>

<!-- Common content of the container elements -->
<ng-template #content>
  The inner content is here...
</ng-template>

有关演示,请参见this stackblitz


如果要在多个地方重复使用该技术,可以将代码包装在组件中:

@Component({
  selector: 'app-p',...
})
export class AppParagraphComponent {
  @Input() useColor = true;
}
<p *ngIf="useColor; else noColorDirective" appColor>
  <ng-container *ngTemplateOutlet="content"></ng-container>
</p>
<ng-template #noColorDirective>
  <p><ng-container *ngTemplateOutlet="content"></ng-container></p>
</ng-template>
<ng-template #content>
  <ng-content></ng-content>
</ng-template>

然后可以用作:

<app-p [useColor]="useColorDirective">
  This is the content!!!
</app-p>

有关演示,请参见this stackblitz。您可能需要为每种类型的元素定义一个不同的组件,可以在其上有条件地应用color指令。

本文链接:https://www.f2er.com/2594743.html

大家都在问