I have a form with few data fields and two buttons.I want to enable the buttons only if the user makes some changes to the form. I have tried using:
this.form.valueChanges.subscribe(data => console.log('form changes', data));
But the changes are detected initially when the form loads also. Is there any other way to check for any changes in the form. I want it to be called only when user makes changes to the field and not when the form loads. Following is my html and typescript code:
profile.html:
<section>
<div>
<form [formGroup]="form">
<fieldset>
<div class="panel-group m-l-1 m-r-1 accordion vertical-scroll" id="">
<div class="form-group required no-gutter">
<label for="firstname"> First Name:</label>
<div class="col-md-7 col-lg-6">
<input type="text" class="form-control" id="firstname" placeholder="" name="firstname" title="firstname" formControlName="firstname" size="128" aria-required="true" maxlength="35">
</div>
</div>
</div>
</fieldset>
<div>
<button class="btn btn-primary" type="button" (click)="save()">Save</button>
<button class="btn btn-primary" type="button" (click)="cancel()">Cancel</button>
</div>
</form>
</div>
</section>
profile.component.ts:
export class ProfileComponent implements OnInit, AfterViewInit, OnChanges {
public form: FormGroup;
constructor(private formBuilder: FormBuilder, private app: Application) {
}
loadForm(): void {
this.form = this.formBuilder.group({
firstname: [this.app.firstName, Validators.required]
});
this.form.valueChanges.subscribe(data => console.log('form changes', data));
}
save(): void {
}
cancel(): void {
};
ngOnInit() {
this.loadForm();
}
ngAfterViewInit() {
this.loadForm();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…