Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 - auto focus dynamic input [duplicate]

Tags:

angular

I have two components, they are like this

MessageComponent.ts

@Component({
        selector: 'Message',
        template: `
            <InlineReply *ngIf="show"></InlineReply>
            <a *ngIf="!show" (click)="toggleForm()">reply</a>
        `
    })
    export class Message {
        public show: boolean = false
        toggleForm(){
            this.show = this.show ? false : true
        }
        onSub(status: boolean){
            this.toggleForm()
        }
    }

InlineReplyComponent.ts

  @Component({
        selector: 'InlineReply',
        template: `
            <form (ngSubmit)="onSubmit()">
                <input name="message" placeholder="Reply..." />
                <button type="submit" disabled>Post</button>
            </form>
        `
    })
    export class InlinePost{
        onSubmit(): void {
            this.submitted = true;
        }
    }

What it does is, when you click the reply link in MessageComponent, a form will show up.

What I want to do is, when the form shows, the input will auto focus. Any idea?

Edit: The answer on similar topic doesn't work for this code

like image 342
angry kiwi Avatar asked Sep 05 '26 09:09

angry kiwi


1 Answers

import { Component, ViewChild, AfterViewInit } from '@angular/core';

@Component({
        selector: 'InlineReply',
        template: `
            <form (ngSubmit)="onSubmit()">
                <input name="message" #msgFocous placeholder="Reply..." />
                <button type="submit" disabled>Post</button>
            </form>
        `
    })

    export class InlinePost implements AfterViewInit {

       @ViewChild('msgFocous') vc: any;

       ngAfterViewInit() {
          this.vc.nativeElement.focus();
       }

       onSubmit(): void {
          this.submitted = true;
       }
    }

the above code is work if any problem just check once AfterViewInit() method in angular2.io

like image 52
yala ramesh Avatar answered Sep 08 '26 05:09

yala ramesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!