【问题标题】:How to set classes for an HTML reference from within the HTML code Angular?如何从 HTML 代码 Angular 中为 HTML 引用设置类?
【发布时间】:2021-11-16 12:39:24
【问题描述】:

我有一个文本区域的引用

<*wrapper-component (submit)="tx1.value ? submit(tx1.value) : tx1.setClass('required')??">
<textarea #tx1> <textarea>
</*wrapper-component>

我将值传递给我的 提交函数,是否可以从 HTML 本身为我的 tx1 元素设置类,而不是创建 ViewChild 属性并访问 elRef.nativeElement.setClass用打字稿?

【问题讨论】:

    标签: html angular typescript elementref


    【解决方案1】:

    我通常建议使用[ngClass] 绑定来动态设置 CSS 选择器。但是,如果您坚持使用模板 ref 变量,则可以使用 setAttribute() 方法设置属性,在您的情况下为 'class'

    <*wrapper-component (submit)="tx1.value ? submit(tx1.value) : tx1.setAttribute('class', 'required')">
      <textarea #tx1> <textarea>
    </*wrapper-component>
    

    【讨论】:

    • 感谢您的回答!我使用 tx1.classList.add('required') 是因为我想保留 textarea 元素上已经存在的类。
    猜你喜欢
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2014-08-16
    • 1970-01-01
    • 2018-07-12
    • 2013-07-12
    • 1970-01-01
    相关资源
    最近更新 更多