【问题标题】:How to properly set IDs on Angular components' input elements?如何在 Angular 组件的输入元素上正确设置 ID?
【发布时间】:2018-12-28 04:03:21
【问题描述】:

我正在想办法解决这种情况。我有一个 Angular 组件,可以构建一张卡片,其中包含您可以编辑的员工信息,我有复选框、文本字段等。

此组件在单个页面上多次构建,每个注册员工的一个组件实例。我与checkbox 输入的id 属性发生冲突;由于组件是多次构建的,当我点击第二张卡片上的复选框时,选中的框实际上是第一张卡片上的那个。

这是我在组件模板上的结构。

<input type="checkbox" [attr.readonly]="editAgentState ? null : 'readonly'" checked id="card-weekday-mon" class="weekday"
                />
                <label for="card-weekday-mon">Mo</label>
                <input type="checkbox" checked id="card-weekday-tue" class="weekday" />
                <label for="card-weekday-tue">Th</label>
                <input type="checkbox" checked id="card-weekday-wed" class="weekday" />
                <label for="card-weekday-wed">We</label>
                <input type="checkbox" checked id="card-weekday-thu" class="weekday" />
                <label for="card-weekday-thu">Tu</label>
                <input type="checkbox" checked id="card-weekday-fri" class="weekday" />
                <label for="card-weekday-fri">Fr</label>
                <input type="checkbox" id="card-weekday-sat" class="weekday" />
                <label for="card-weekday-sat">Sa</label>
                <input type="checkbox" id="card-weekday-sun" class="weekday" />
                <label for="card-weekday-sun">Su</label>
              </div>

所以我试图找到为每个复选框设置动态Id 的最佳方法,以便点击影响被点击的确切复选框。

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    您可以使用 ts 文件中的变量作为 div 的 id,例如

    <input type="checkbox" [attr.readonly]="editAgentState ? null : 'readonly'" checked id={{employee.name}} class="weekday"/>
    

    您可以从您的 ts 文件中填充员工姓名。这样,您的组件的每个实例都将具有单独的 id。

    【讨论】:

      【解决方案2】:

      使用此代码,您可以为每个组件实例 (ngOnInit) 中的输入和标记 HTML 标记生成一个随机 ID,但您可以使用 TS 文件中的任何其他变量来设置它。

      在 TS 文件中:

      id: string = 'id';
      
      ngOnInit(): void {
         this.idGenerator();
      }
      
      idGenerator(): void {
         this.id += Math.random().toString().slice(2);
      }
      

      在 HTML 文件中:

      <input [id]="id" />
      <label [for]="id">Label Text</label>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-09
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 2014-12-25
        • 2022-10-20
        • 1970-01-01
        相关资源
        最近更新 更多