Angular自定义指令-生成id,带入到for中
前言
在前端项目中,经常遇到这种需求:点击一个label标签,自动将焦点放在对应的input上。
一般情况下我们会为input指定一个id,然后再在label的for属性中使用这个id:
<label for="myCustomId"></label>
<input type="text" id="myCustomId">
在Angular中,组件是可以被多个位置进行多次引用,最终生成多个实例的,这样的话id就不能固定写死了。
此时我们可以定义一个指令,来更方便的生成id,以及和对应的label-for做映射。
指令的写法
import { Directive, ElementRef, Input, Renderer2 } from '@angular/core';
@Directive({
selector: '[ngxFor],[ngxId]',
})
export class NgxIdDirective {
@Input('ngxFor') ngxFor?: any;
constructor(private elRef: ElementRef, private renderer: Renderer2) {
}
ngOnInit(): void {
if (!this.ngxFor)
this.renderer.setAttribute(this.elRef.nativeElement, 'id', this.generateUUID());
}
ngAfterViewInit() {
if (this.ngxFor)
this.renderer.setAttribute(this.elRef.nativeElement, 'for', this.ngxFor.id);
}
private generateUUID(): string {
let temp_url = URL.createObjectURL(new Blob());
let uuid = temp_url.toString();
URL.revokeObjectURL(temp_url);
return uuid.substr(uuid.lastIndexOf('/') + 1);
}
}
html中的使用方法
在html中可以像下面这样使用,下面的例子中使用了3次:
<label [ngxFor]="fieldNameRequire">是否必填</label>
<input type="checkbox" ngxId #fieldNameRequire>
<br>
<label [ngxFor]="objectFieldNameRequire">是否必填</label>
<input type="checkbox" ngxId #objectFieldNameRequire>
<br>
<label [ngxFor]="arrayFieldNameRequire">是否必填</label>
<input type="checkbox" ngxId #arrayFieldNameRequire>