【问题标题】:Is there any way to add or remove directive using condition in angular framework?有没有办法在角度框架中使用条件添加或删除指令?
【发布时间】:2019-09-09 08:42:04
【问题描述】:

我在单击事件上使用指令选择器,它提供 asc 和 desc,但我想在我的反应形式脏时删除此指令。 appSortable 是指令选择器

<div class="bank-name sort" appSortable sortDirection="asc" (sorted)="onSortedBankName($event)" (click)="sortColumnBy(bankConstants.sortBy.name)"  #Sortable>

【问题讨论】:

标签: angular angular-directive


【解决方案1】:

为什么不在模板中使用 *ngIf?

<div *ngIf="myForm.dirty" class="bank-name sort">
<div *ngIf="!myForm.dirty" class="bank-name sort" appSortable sortDirection="asc" (sorted)="onSortedBankName($event)" (click)="sortColumnBy(bankConstants.sortBy.name)"  #Sortable>

【讨论】:

  • 在点击事件中我需要检查表单是否脏了,然后警告模型将显示如果用户点击“是”如何存储以前的 sortDirection = (asc 或 desc) 和 sortBy
【解决方案2】:

您不能更新指令以接受启用的属性,然后将其设置为表单的状态吗?

[isEnabled]="!myForm.dirty"

如果此值为 false,则让您的指令不执行任何操作。

【讨论】:

    【解决方案3】:

    只有当代码是 1-liner 时,才有两个相似的代码。如果它跨越多行,代码可能很快就会变得丑陋。

    您的指令可以有一个输入参数。您可以将 form.dirty 的值传递给指令并在此处应用您想要的任何逻辑。它还使您免于重复代码。

    参见示例here

    编辑:使解决方案更加通用,每个组件都可以有自己的功能并进行相应的排序。

    【讨论】:

      【解决方案4】:

      如果表单脏了,你可以使用下面的代码来隐藏你的内容

      <div *ngIf="!YourFormName.dirty" class="bank-name sort" appSortable sortDirection="asc" (sorted)="onSortedBankName($event)" (click)="sortColumnBy(bankConstants.sortBy.name)"  #Sortable>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 2019-04-26
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 2019-10-29
        相关资源
        最近更新 更多