Angular 2 - 自动聚焦动态输入

3
我有两个组件,它们是这样的:

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;
        }
    }

它的作用是,当你在MessageComponent中点击回复链接时,一个表单会出现。
我想做的是,当表单显示时,输入框自动聚焦。有什么想法吗?
编辑:类似主题的答案对此代码无效。

那不起作用。 - angry kiwi
1个回答

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;
       }
    }

如果有任何问题,请检查Angular2.io中的AfterViewInit()方法。以上代码在正常情况下应该能够工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接