我创建了一个指令来聚焦输入,如果它无效
import { Directive, Input, Renderer2, ElementRef, OnChanges } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[focusOnError]'
})
export class HighlightDirective implements OnChanges {
@Input() submitted: string;
constructor(private renderer: Renderer2, private el: ElementRef) { }
ngOnChanges(): void {
const el = this.renderer.selectRootElement(this.el.nativeElement);
if (this.submitted && el && el.classList.contains('ng-invalid') && el.focus) {
setTimeout(() => el.focus());
}
}
}
我确实有一个带有两个输入的反应式表单,并且我已经将该指令应用于两个输入
<form>
...
<input type="text" id="familyName" focusOnError />
...
<input type="text" id="appointmentCode" focusOnError />
...
</form>
提交表单后,它工作正常,但我正在努力实现以下几点:
预期成果: - 提交表格后,如果两个输入都无效,则只应关注第一个输入。
当前结果: - 提交表格后,如果两个输入都无效,则第二个输入得到关注。
我不知道如何指定"只有在它是第一个孩子时才这样做",我已经尝试过使用指令的选择器,但没有运气。
有什么想法吗?
提前非常感谢。
为了控制表单的输入,我认为更好的解决方案是使用 ViewChildren 获取所有元素。因此,我们可以循环这些元素并关注第一个元素。
因此,我们可以有一个辅助的简单指令:
@Directive({
selector: '[focusOnError]'
})
export class FocusOnErrorDirective {
public get invalid()
{
return this.control?this.control.invalid:false;
}
public focus()
{
this.el.nativeElement.focus()
}
constructor(@Optional() private control: NgControl, private el: ElementRef) { }
}
而且,在我们的组件中,我们有一些类似的
@ViewChildren(FocusOnErrorDirective) fields:QueryList<FocusOnErrorDirective>
check() {
const fields=this.fields.toArray();
for (let field of fields)
{
if (field.invalid)
{
field.focus();
break;
}
}
}
您可以在堆栈闪电战中看到行动
更新总是事情可以改进:
为什么不创建一个应用于表单的指令?
@Directive({
selector: '[focusOnError]'
})
export class FocusOnErrorDirective {
@ContentChildren(NgControl) fields: QueryList<NgControl>
@HostListener('submit')
check() {
const fields = this.fields.toArray();
for (let field of fields) {
if (field.invalid) {
(field.valueAccessor as any)._elementRef.nativeElement.focus();
break;
}
}
}
所以,我们.html
就像<form [formGroup]="myForm" focusOnError>
<input type="text" formControlName="familyName" />
<input type="text" formControlName="appointmentCode" />
<button >click</button>
</form>
查看堆叠闪电战
更重要的是,如果我们用作选择器形式
@Directive({
selector: 'form'
})
甚至我们可以删除表单中的焦点错误
<form [formGroup]="myForm" (submit)="submit(myForm)">
..
</form>
更新 2表单组与表单组的问题。解决
NgControl只考虑具有[(ngModel)],formControlName和[formControl]的控件,因此。如果我们可以使用这样的表单
myForm = new FormGroup({
familyName: new FormControl('', Validators.required),
appointmentCode: new FormControl('', Validators.required),
group: new FormGroup({
subfamilyName: new FormControl('', Validators.required),
subappointmentCode: new FormControl('', Validators.required)
})
})
我们可以使用这样的形式:
<form [formGroup]="myForm" focusOnError (submit)="submit(myForm)">
<input type="text" formControlName="familyName" />
<input type="text" formControlName="appointmentCode" />
<div >
<input type="text" [formControl]="group.get('subfamilyName')" />
<input type="text" [formControl]="group.get('subappointmentCode')" />
</div>
<button >click</button>
</form>
在 .ts 中,我们有
get group()
{
return this.myForm.get('group')
}
使用 Angular 3 更新 8你可以得到孩子的后代,所以它只是写
@ContentChildren(NgControl,{descendants:true}) fields: QueryList<NgControl>
好吧,只是为了有趣的堆栈闪电战。如果我们有一个formControl,我们可以注入ngControl,它是控件本身。因此,我们可以获取表单组。我控制"提交"在应用程序组件中变通
<button (click)="check()">click</button>
check() {
this.submited = false;
setTimeout(() => {
this.submited = true;
})
}
指令就像
export class FocusOnErrorDirective implements OnInit {
@HostListener('input')
onInput() {
this._submited = false;
}
//I used "set" to avoid ngChanges, but then I need the "ugly" work-around in app.component
@Input('focusOnError')
set submited(value) {
this._submited = value;
if (this._submited) { ((is submited is true
if (this.control && this.control.invalid) { //if the control is invalid
if (this.form) {
for (let key of this.keys) //I loop over all the
{ //controls ordered
if (this.form.get(key).invalid) { //If I find one invalid
if (key == this.control.name) { //If it's the own control
setTimeout(() => {
this.el.nativeElement.focus() //focus
});
}
break; //end of loop
}
}
}
else
this.el.nativeElement.focus()
}
}
}
private form: FormGroup;
private _submited: boolean;
private keys: string[];
constructor(@Optional() private control: NgControl, private el: ElementRef) { }
ngOnInit() {
//in this.form we has the formGroup.
this.form = this.control?this.control.control.parent as FormGroup:null;
//we need store the names of the control in an array "keys"
if (this.form)
this.keys = JSON.stringify(this.form.value)
.replace(/[&/\#+()$~%.'"*?<>{}]/g, '')
.split(',')
.map(x => x.split(':')[0]);
}
}