import { Component } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-my-form',
template:
})
export class MyFormComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ name: [''], email: [''] }); } }
import { Component, ViewChild, Renderer2 } from '@angular/core'; import { FormControl } from '@angular/forms';
@Component({
selector: 'app-my-form',
template:
})
export class MyFormComponent {
@ViewChild('nameInput') nameInput;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() { this.renderer.selectRootElement(this.nameInput.nativeElement).focus(); }
get myFormControl(): FormControl { return this.myForm.get('name') as FormControl; } }
用上述方法,可以实现在不需要按钮的情况下,在页面加载时自动打开表单。