我正在重構一個指令,該指令在滑鼠懸停/焦點的表單控制元件上添加某種工具提示。使用起來很簡單。只需將其添加到元素并定義其文本。您用于文本的輸入還定義了工具提示的樣式
<!-- Creates red tooltip -->
<input matInput type="text" libMessage [libError]="'Error Text'" />
<!-- Creates blue tooltip -->
<input matInput type="text" libMessage [libInfo]="'Info Text'" />
<!-- Creates yellow tooltip -->
<input matInput type="text" libMessage [libWarning]="'Warning Text'" />
我們收到了擴展它的請求,可以選擇不僅顯示文本,還顯示自定義組件,它提供了更好的樣式選項。它有效,但感覺有點麻煩。[libError]您必須通過提供非空字串的值來指定它的型別,而不是僅僅提供一個組件。
<!-- Creates red tooltip from simple text -->
<input matInput type="text" libMessage [libError]="'Error Text'" />
<!-- Creates a tooltip from component with red background. Text is ignored. -->
<input matInput type="text" libMessage [libError]="'Error Text'" [libCustomComponent]="someComponent" />
我提供了幾種解決方法,但想知道是否可以讓指令的輸入以兩種方式作業。同時作為輸入和屬性。如果與 value 一起使用,它定義文本,如果單獨使用,它定義樣式但必須提供組件。像這樣的東西。
<!-- [libError] specifies the text and type -->
<input matInput type="text" libMessage [libError]="'Error Text'" />
<!-- libError defines just a style, no value is needed. -->
<input matInput type="text" libMessage libError [libCustomComponent]="someComponent" />
有可能做這樣的事情嗎?
uj5u.com熱心網友回復:
是的,這是可能的,但是您需要將您的libError屬性轉換為布林值。要獲得更好的概述,請查看布爾屬性強制轉換(CDK 就是這樣做的)。
對于使用示例,我們可以查看mat-divider. 它使用布爾強制來允許我們寫一些像這樣簡單的東西:
<mat-divider vertical />
每當我們需要垂直分隔線時。
uj5u.com熱心網友回復:
我認為您可以使用可以使用 @Input 接受值并為 @Input 裝飾器提供一些默認值的指令來實作這一點。因此,一旦您在向 DOM 元素添加指令時提供了輸入值,它就會接受并按照輸入值行事,否則如果未提供值,指令將使用您為 @Input 設定的默認值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491833.html
