In our project, we used Angular Formly to generate complex forms (with complex grouping). I checked the component documentation, but I couldn't find any sample or solution for finding the first editable component (like a textbox
) and set the focus on it when the form or component is loaded.
1 Answer
When we want to check a "group of any" It's util use a directive. A Directive with a selector of formControl and formControlName like
@Directive({
selector: '[formControl], [formControlName]'
})
export class InputDirective {
constructor(private controlDir: NgControl,private el:ElementRef) { }
}
Give access to all the "inputs" control by a FormControlName or a FormControl
In our form, we can get all of them using viewChildren
@ViewChildren(InputDirective) inputs:QueryList<InputDirective>
And in ngAfterViewInit we can make some like
ngAfterViewInit()
{
const input=this.inputs?this.inputs.find(x=>x.controlDir.enabled):null
if (input)
input.el.nativeElement.focus()
}
focus: true
to yourFormlyFieldConfig
of your first element in the array.