我在一个组件中有一个表单标签,在另一个单独的组件中有关联的可重用自定义输入。我之所以这样设计它,是因为有时我想要一个带有自定义输入的标签,有时我不想。有时我希望标签位于自定义输入之上,有时我希望它与自定义输入内联。因此,单独的组件是有意义的。它看起来像这样(尽管父组件中的标记可能会有所不同):
component1.component.html:
<label for="myInput">Label Text</label>
<app-component2></app-component2>component2.component.html
<input id="myInput" ... loads of custom stuff here>唯一的问题是label for和input id不工作。当我单击标签时,当输入位于另一个组件中时,它不会选择输入。我怎么才能让它工作呢?
谢谢
发布于 2019-11-09 07:39:18
您可以将这两个组件包装到一个父组件中,并可以通过单击标签发出一个事件来传递所需的id。
您的代码将如下所示
Parentcomponent.html
<parentComponent>
<component1 (emitId) ='setLabelId($event)'></component1>
<component2 [labelId]='labelId'></component2>
</parentComponent>parentComponent.ts将会是
export class parentComponent implements OnInit {
const labelId : string;
constructor() { }
ngOnInit() {
}
setLabelId(id:string){
this.labelId = id;
}
}component1.ts将如下所示
export class Component1 implements OnInit {
@Output() emitId = new EventEmitter<string>();
constructor() { }
ngOnInit() {
}
handleLabelClick(id:string){
this.emitId.emit(id);
}
}component1.html
<label onClick="handleLabelClick(myInput)" for="myInput">其中component2.ts将类似于
export class Component2 implements OnInit {
@Input() labelId:string
constructor() { }
ngOnInit() {
// this.labelId holds the value of required id
}
}和component2.html
<input id="myInput" ... loads of custom stuff here>发布于 2019-11-11 17:33:26
我通过这样做让它工作起来:
<label>
<span>Label Text</span>
<app-component2></app-component2>
</label>其中app-component2包含输入元素。
发布于 2019-11-11 18:13:43
您可以传递id属性,方法是将id作为表单读取,将其呈现给模板中的@Input元素,然后在模板启动后将其从主机元素中删除(因为html必须是唯一的)。
export class Component2 implements AfterContentInit {
@Input() id: string;
constructor(
private readonly _elementRef: ElementRef,
private readonly _renderer: Renderer2
) {}
ngAfterContentInit(): void {
// or rewrite it to another non-unique attribute
this._renderer.removeAttribute(this._elementRef.nativeElement, 'id');
}
}在Component2模板中
<input id="{{id}}">这允许Component1使用Component2的选择器,就好像它是一个输入元素一样。
<label for="myInput">Label Text</label>
<app-component2 id="myInput"></app-component2>https://stackoverflow.com/questions/58774858
复制相似问题