HTML代码:
<form [formGroup]="form">
<div class="form-group">
<label for="searchBox1">Search Box 1</label>
<input type="text" class="form-control" id="searchBox1" name="searchBox1"
formControlName="searchBox" placeholder="Search Box 1" (change)="addText($event.target.value)">
</div>
<div class="form-group">
<label for="searchBox2">Search Box 2</label>
<input type="text" class="form-control" id="searchBox2" name="searchBox2"
formControlName="searchBox" placeholder="Search Box 2" (change)="addText($event.target.value)">
</div>
</form>
组件
代码:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
'searchBox': new FormControl(null, Validators.required)
});
}
addText(value) {
this.form.setValue({
'searchBox': value
});
}
}