angular - 标签上的 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 {
}
}
解决方案
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>
推荐阅读
- swift - SwiftUI -> 线程 1:致命错误:未找到 ModelData 类型的 ObservableObject
- javascript - 在导入的函数之间使用范围变量的最佳实践
- python - 通过 ms gragh core api python 发送电子邮件
- python - 必须编写一个程序来平均所有数字。并苦苦挣扎从哪里开始
- locust - 如何在 Locust 中模拟用户帐户衰减?
- google-chrome-devtools - Chrome DevTools:有没有办法使用网络 API 计算排队时间?
- mysql - 如何防止 gorm 忽略 .Updates() 子句中“UpdatedAt”字段的值?
- r - slackr_setup() 回归:if (nrow(chan) == 0) { 中的错误:参数长度为零
- html - localhost 仅在我的计算机中有效,在我的本地网络中无效
- python - 如果模式具有相同的计数值 Python,则接受字符串