- import
FormControl
:
import {
FormControl } from '@angular/forms';
Create an name
instance type FormControl
:
name = new FormControl('Jerry');
The initial value is FormControl
set .
- In the HTML file, create a binding relationship between element and the Component
name
property :
After this, the value of the Component name attribute will be automatically passed to the HTML element:
This way, form controls and DOM elements can communicate with each other: the view reflects changes in the model, and the model reflects changes in the view.
Use .value
to access the value of the FormControl instance:
<label for="name">Name: </label>
<input id="name" type="text" [formControl]="name">
<p>显示控件的值: {
{ name.value }}</p>
How to use setValue
to modify the value of FormControl
updateName() {
this.name.setValue('Nancy');
}
After clicking the button:
The value becomes nancy:
See the unified processing of the click response event zone.js
in :
Finally call core.js
in executeListenerWithErrorHandling
:
Execute setValue:
How to respond to user input
constructor(){
this.name.valueChanges.subscribe(selectedValue => {
console.log('value changed: ', selectedValue);
})
}
Effect:
Found from the call stack, still executeListenerWithErrorHandling
:
EventEmitter
Send an update via :
ng-untouched ng-pristine ng-valid
When are these three classes assigned values?
- ng-untouched The field has not been touched yet
- ng-pristine The field has not been modified yet
- ng-valid The field content is valid
How to use form groupsform group
Create FormGroup
a .
Its constructor is a json object, and the property type is FormControl
.
FormGroup can also use methods setValue
such as .
The form group can also track the state of each control and its changes, so if the state or value of one of the controls changes, the parent control will also emit a new state change or value change event.
How to bind the FormGroup property to the HTML file:
<form [formGroup]="profileForm">
<label for="first-name">First Name: </label>
<input id="first-name" type="text" formControlName="firstName">
<label for="last-name">Last Name: </label>
<input id="last-name" type="text" formControlName="lastName">
</form>
The property provided by the FormControlName
directive binds formControlName
each input box FormGroup
to the one defined in . The data in the FormGroup group can also be monitored by :表单控件
valueChanges
this.profileForm.valueChanges.subscribe(
value => {
console.log('group value: ', value);
}
);
Use setValue
to modify the value of group:
this.profileForm.setValue(
{
firstName: 'Tom',
lastName: "Tom1"
}
);
The submit event emitted by the form tag is a built-in DOM event, which can be triggered by clicking a button of type submit. This also allows the user to submit the completed form with the Enter key.
Add a button to the bottom of the form to trigger the form submission.
onSubmit(){
console.warn(this.profileForm.value);
}