【问题标题】:Angular 2+ How to use an variable value to call a directive?Angular 2+ 如何使用变量值来调用指令?
【发布时间】:2018-11-11 19:43:44
【问题描述】:

我使用的是材质角度,常规按钮是

<button mat-button> x </button> or <button mat-raised-button> x </button>

我有一个字符串变量,我们称之为'type',它的值可以是'mat-button'或'mat-raised-button',我可以使用这个变量调用按钮的'directive'吗?类似:

<button [type]> x </button>

上面的这种情况更像是我正在尝试做的一个例子,但为了简单起见,问题是如何使用变量值“使用”指令

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    你可以使用 ngSwitch 来创建你的模板

    <ng-container [ngSwitch]="type">
      <ng-template [ngSwitchCase]= "'mat-button'">
        <button mat-button></button>
      </ng-template>
      <ng-template [ngSwitchCase]= "'mat-raised-button'">
         <button mat-raised-button></button>
      </ng-template>
      <ng-template ngSwitchDefault> No Direction </ng-template>
    </ng-container> 

    【讨论】:

    • 这是一个很好的答案,但我已经这样做了。我想创建一些会使用更多选项的情况,并且正在寻找一种更简单的方法
    【解决方案2】:

    &lt;button mat-button&gt;&lt;button mat-raised-button&gt; 实际上是同一个组件,只是应用了不同的 CSS 样式。

    您可以手动更改 CSS 样式来改变按钮的外观。

    <button mat-button [class.mat-button]="!raised" [class.mat-raised-button]="raised">Hello World</button>
    

    更新:

    <button mat-button [class]="type">Hello World</button>
    

    其中类型的值可以是字符串mat-buttonmat-raised-button

    【讨论】:

    • 感谢您的回答,但就像我在上一个回答中所说的那样,问题中的案例是一个示例,我也需要一种在其他情况下处理它的方法,如果可能的话将变量值直接放在组件上
    • 好吧,这又只在这种情况下有效,而不是在变量应该触发指令的情况下。但它在这种情况下有效并帮助了我,所以我将此标记为正确答案
    • 请注意使用[class]="type" 绑定 - 在这里可以正常工作,但这样做通常会删除任何已应用的类并将整个类列表替换为绑定变量的值。最好使用[ngClass]="type"来避免这种情况,只需将类值添加到类列表中。
    • @G.Tranter 这是我的意图。 mat-button 指令应用 CSS 样式,然后我需要将其替换为“类型”。但是,是的,当您不知道它以这种方式工作时,它通常是错误的来源。
    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 2019-06-10
    • 2016-11-25
    • 2017-10-28
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多