3

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

angry kiwi
  • 10,730
  • 26
  • 115
  • 161

1 Answers1

6
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

angry kiwi
  • 10,730
  • 26
  • 115
  • 161
yala ramesh
  • 3,362
  • 1
  • 22
  • 35