如何在选择某个 mat-option 或不选择它时启用输入字段?

huangapple go评论72阅读模式
英文:

How to enable input fields if a certain mat-option is selected or not?

问题

根据这个主题的已接受答案,我成功获取了所点击选项的选定状态。我想根据某个选项的选择来禁用一个输入。使用下面的示例,我能够在任何选项被选中/取消选中时启用/禁用输入。例如,我希望仅在第二个选项(蘑菇)未选中时禁用输入字段。如果第二个选项被选中,输入字段将能够启用。我该如何做?

StackBlitz 示例

英文:

Based on this topic's accepted answer, I managed to get the selected state of the clicked option. I want to disable an input based on a selection of a certain option. With the below example, I am able to enable/disable the input when any option is checked/unchecked. For example, I want to disable the input field only if the second option (Mushroom) is unchecked. If the second option is checked, the input field could be enabled. How could I do it?

StackBlitz Example

答案1

得分: 1

你可以通过将你的formcontrol的值附加到mat-input的[disabled]指令来实现这一点。

  1. 仅仅读取toppings(form control)的值
isValueSelected(): boolean {
    var valueArray: any = this.toppings.value || [];
    console.log(valueArray, valueArray.includes('Mushroom'));
    return !valueArray.includes('Mushroom');
}
  1. 将其附加到[disabled]指令
<input id="numeDB_SQLite" type="text" name="numeDB_SQLite" [disabled]="isValueSelected()"/>

我已经在你的StackBlitz中进行了更新,在这里。如果有帮助,请进行点赞/选择。

英文:

You can achive this by attaching your formcontrol value to mat-input's [disabled] directive.

1)just read toppings(form control) value

isValueSelected(): boolean {
    var valueArray: any = this.toppings.value || [];
    console.log(valueArray, valueArray.includes(&#39;Mushroom&#39;));
    return !valueArray.includes(&#39;Mushroom&#39;);
 }

2)attach it to [disabled] directive

&lt;input id=&quot;numeDB_SQLite&quot; type=&quot;text&quot; name=&quot;numeDB_SQLite&quot; [disabled]=&quot;isValueSelected()&quot;/&gt;

i have updated your stackblitz here. please upvote/select if helps.

答案2

得分: 0

Sure, here are the translated code snippets:

如果想要在选择某个值时禁用

    &lt;input id=&quot;numeDB_SQLite&quot; type=&quot;text&quot; matInput 
          [disabled]=&quot;toppings?.value &amp;&amp; toppings.value.length&quot; ../&gt;

如果想要在选择一个元素时禁用,例如

    &lt;input id=&quot;numeDB_SQLite&quot; type=&quot;text&quot; matInput 
              [disabled]=&quot;toppings?.value &amp;&amp; toppings.value.includes(&#39;Mushroom&#39;)&quot; ../&gt;
英文:

If want disabled if some value is selected

&lt;input id=&quot;numeDB_SQLite&quot; type=&quot;text&quot; matInput 
      [disabled]=&quot;toppings?.value &amp;&amp; toppings.value.length&quot; ../&gt;

If want disabled when one element is selected, e.g.

&lt;input id=&quot;numeDB_SQLite&quot; type=&quot;text&quot; matInput 
          [disabled]=&quot;toppings?.value &amp;&amp; toppings.value.includes(&#39;Mushroom&#39;)&quot; ../&gt;

huangapple
  • 本文由 发表于 2023年4月19日 15:56:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定