Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

forms - How do I programmatically set focus to dynamically created FormControl in Angular2

I don't seem to be able to set focus on a input field in dynamically added FormGroup:

addNewRow(){
    (<FormArray>this.modalForm.get('group1')).push(this.makeNewRow());
    // here I would like to set a focus to the first input field
    // say, it is named 'textField'

    // but <FormControl> nor [<AbstractControl>][1] dont seem to provide 
    // either a method to set focus or to access the native element
    // to act upon
}

How do I set focus to angular2 FormControl or AbstractControl?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I made this post back in December 2016, Angular has progressed significantly since then, so I'd make sure from other sources that this is still a legitimate way of doing things


You cannot set to a FormControl or AbstractControl, since they aren't DOM elements. What you'd need to do is have an element reference to them, somehow, and call .focus() on that. You can achieve this through ViewChildren (of which the API docs are non-existent currently, 2016-12-16).

In your component class:

import { ElementRef, ViewChildren } from '@angular/core';

// ...imports and such

class MyComponent {
    // other variables
    @ViewChildren('formRow') rows: ElementRef;

    // ...other code
    addNewRow() {
        // other stuff for adding a row
        this.rows.first().nativeElement.focus();
    }
}

If you wanted to focus on the last child...this.rows.last().nativeElement.focus()

And in your template something like:

<div #formRow *ngFor="let row in rows">
    <!-- form row stuff -->
</div>

EDIT:

I actually found a CodePen of someone doing what you're looking for https://codepen.io/souldreamer/pen/QydMNG


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...