【问题标题】:Angular 'for' attribute on label only works on first input标签上的 Angular 'for' 属性仅适用于第一个输入
【发布时间】:2020-02-27 02:06:07
【问题描述】:

我正在学习 Angular 并且有一个小型测试组件(Angular 9 - 使用 CLI 全新安装)。

我有两个输入,并试图通过将 id 放在“for”属性中来将每个标签与其输入相关联(我知道您也可以将字段包装在标签中)。这适用于第一个输入;单击标签会将焦点设置为输入。但是,单击第二个标签也会将焦点设置到 first 输入。如果我交换输入的位置并不重要,行为是相同的。

为什么会这样?一般来说,有没有更好的方法来做到这一点?我觉得我错过了什么。

restool.component.html

<div>
    <label [for]="origin">Origin</label>
    <input [formControl]="origin" [attr.id]="origin">
</div>
<div>
    <label [for]="destination">Destination</label>
    <input [formControl]="destination" [attr.id]="destination">
</div>

retool.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-restool',
  templateUrl: './restool.component.html',
  styleUrls: ['./restool.component.css']
})
export class RestoolComponent implements OnInit {

  origin = new FormControl('');
  destination = new FormControl('');

  constructor() {

   }

  ngOnInit(): void {
  }

}

【问题讨论】:

    标签: angular


    【解决方案1】:

    尝试使用普通的 HTML,destinationorigin 可能是对象类型。

    <div>
        <label for="origin">Origin</label>
        <input [formControl]="origin" id="origin">
    </div>
    <div>
        <label for="destination">Destination</label>
        <input [formControl]="destination" id="destination">
    </div>
    

    【讨论】:

    • 这确实适用于这个简单的场景。但我看到的大多数例子都是动态完成的。如果我以这种方式构建组件,我不会将 ID 泄漏到可能与其他组件发生冲突的全局范围内吗?我认为这是 Angular 组件的优点之一——它们非常独立。
    • 嗯,总有办法解决您的顾虑。例如,如果您打算一遍又一遍地重用这个组件,您可以使用@Input() originId(对destinationId 执行相同的操作)并每次在此处传入一个唯一的id(与来自API 的id 或循环的索引相关) )。如果你不打算一遍又一遍地重用这个组件,你可以将 id 更改为 RestoolComponentDestinationRestToolComponentOrigin 如果你害怕你将有 origindestination 作为一个 ID不同的组件(发生这种情况的可能性也很小)。
    • 拥有唯一 ID 似乎很奇怪,我必须强制父母传递一些唯一的东西(即使它在那里是唯一的,其他地方呢?),或者猜测一个 ID对于整个 HTML 文档将是唯一的。我在这里(github.com/angular/angular/issues/5145)和这里(stackoverflow.com/questions/60114682/…)找到了关于这个的讨论。也许这个想法是避免使用 ID,但有时您必须(用于可访问性的 aria 属性)。我会接受,但我仍然想知道处理 ID 的最佳方式。
    猜你喜欢
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2018-10-30
    • 1970-01-01
    相关资源
    最近更新 更多