我有两个组件,它们就像这样
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中的回复链接时,将显示一个表单。
我想要做的是,当表单显示时,输入将自动对焦。有什么想法吗?
编辑:类似主题的答案对此代码不起作用
答案 0 :(得分:4)
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()方法