markdown Angular - 在输入字段中监听变化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Angular - 在输入字段中监听变化相关的知识,希望对你有一定的参考价值。
# Angular - Listen For Changes In An Input Field
[SOURCE](https://angular.io/guide/reactive-forms#observe-control-changes), [SOURCE](https://angular.io/guide/component-interaction)
The cleanest way to do this (so far), is to [observe control changes](https://angular.io/guide/reactive-forms#observe-control-changes).
`appointment-reason.component.html`:
```html
<div id="ReasonInput" fxLayout="row">
<mat-form-field appearance="standard" fxFlex color="accent" [formGroup]="reasonForm">
<mat-label>{{'AppointmentReason.reason_title_optional' | translate}}</mat-label>
<input matInput [placeholder]="'AppointmentReason.reason_input_placeholder' | translate"
[formControlName]="reasonInputName">
</mat-form-field>
</div>
<div fxLayout="row" fxLayoutAlign="center" id="SkipConfirmButton">
<button class="btn-blue-width100-rounder"
[title]="'AppointmentReason.skip' | translate">
{{ shouldShowConfirm ? ('AppointmentReason.confirm' | translate) : ('AppointmentReason.skip' | translate) }}
</button>
</div>
```
`i18n/en.json` - `i18n/vn.json`:
```json
{
"AppointmentReason" : {
...
"skip": "Skip",
"confirm": "Confirm Reason"
}
}
```
`appointment-reason.component.ts`:
```typescript
@Component({
selector: 'app-appointment-reason',
templateUrl: './appointment-reason.component.html',
styleUrls: ['./appointment-reason.component.scss']
})
export class AppointmentReasonComponent implements OnInit {
private reasonForm: FormGroup;
private readonly reasonInputName = 'reasonInput';
private shouldShowConfirm = false;
constructor(private formBuilder: FormBuilder) {
this.createForm();
this.observeInputChanges();
}
ngOnInit() {
}
private createForm() {
this.reasonForm = this.formBuilder.group({
[this.reasonInputName]: '', // note the [this.reasonInputName] syntax to map the string name to a common variable
});
}
private observeInputChanges() {
const inputControl = this.reasonForm.get(this.reasonInputName);
inputControl.valueChanges.forEach(
(value: string) => this.setShowConfirmButton(value)
);
}
private setShowConfirmButton(value: string) {
if (value) {
this.shouldShowConfirm = true;
} else {
this.shouldShowConfirm = false;
}
}
}
```
## Somewhat relevant:
Another less clean way is to use a property to keep track of the content of the input and then [intercept input property changes with a setter](https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter).
Alternatively, we can [intercept input property changes with ngOnChanges()](https://angular.io/guide/component-interaction#intercept-input-property-changes-with-ngonchanges).
> You may prefer this approach to the property setter when watching multiple, interacting input properties.
以上是关于markdown Angular - 在输入字段中监听变化的主要内容,如果未能解决你的问题,请参考以下文章