首页 > 解决方案 > 标签上的 Angular 'for' 属性仅适用于第一个输入

问题描述

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

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

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

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>

restool.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

解决方案


destination尝试使用常用的 HTML ,它可能origin是对象类型。

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

推荐阅读