Components: Focusing on md-input-container programatically

Created on 8 Feb 2017  路  5Comments  路  Source: angular/components

I have a component that has some md-input-container elements. I would like to set focus on the first one when the view loads.

The way I am implementing this is by creating a @ViewChild property and then calling focus on it ngAfterViewInit. There are no errors but, the focus is still not working.

export class AdminUserComponent implements AfterViewInit {
    @ViewChild(MdInputContainer)
    private firstInput: MdInputContainer;

    ngAfterViewInit() {
        this.firstInput._mdInputChild.focus();
    }
}

I tried setting the focus code in a setTimeout function but that didn't make a difference. Has anyone successfully set focus on a material input when the view loads?

Most helpful comment

Thank you for helping me. I found my problem... I tried with MdInput and it didnt work. Then I tried with MdInputDirective and now it works perfectly.

All 5 comments

Have you tried focusing the actual input instead? As far as I can tell, there is no public method for focusing the input on the container https://github.com/angular/material2/blob/master/src/lib/input/input-container.ts#L251-L380

There is a public method. Its called focus() and its in the documentation. I have tried focusing on the actual input as well. If I do that I get other errors thrown by mdContainer. I was hoping someone could show me an example of how I could auto focus on an md-input when my view loads. It seems like it would be a fairly common use case.

I just linked you the source code of md-input-container, there is no focus() method, nor does the documentation say anything about any focus() method on the MdInputContainer https://material.angular.io/components/component/input

And it seems to be working to me when I focus the input http://plnkr.co/edit/fVQshe6iwOMpDZNd8HCH?p=preview

Thank you for helping me. I found my problem... I tried with MdInput and it didnt work. Then I tried with MdInputDirective and now it works perfectly.

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jelbourn picture jelbourn  路  3Comments

Miiekeee picture Miiekeee  路  3Comments

shlomiassaf picture shlomiassaf  路  3Comments

alanpurple picture alanpurple  路  3Comments

constantinlucian picture constantinlucian  路  3Comments