I work on a bug and I want to prevent user to save the data he don't enter any data in the form. The form is created like this:
private buildAddressPopupForm() {
this.form = this.fb.group({
roles: [''],
addressLine1: [this.data.addressLine1],
addressLine2: [this.data.addressLine2],
city: [this.data.city],
state: [this.data.state],
postalCode: [this.data.postalCode],
country: [this.data.country],
startDate: [],
endDate: [],
isNew: [this.data.isNew],
phone: [this.data.phone],
fax: [this.data.fax],
mobile: [this.data.mobile],
email: [this.data.email],
website: [this.data.website],
active: [this.data.active === undefined ? true : this.data.active],
});
}
I don't have Apply and Cancel Buttons, they came from another library so I overrode them:
createButtons() {
let applyButton = {
label: "apply",
id: "apply",
disabled: true,
onClick: () => this.onApplyPopup()
}
let cancelButton = {
label: "cancel",
id: "cancel",
disabled: false,
onClick: () => this.onClosePopup()
}
this.buttons.push(applyButton);
this.buttons.push(cancelButton);
}
onApplyPopup() {
if (this.form.valid) {
this.applyPopup.emit(this.form.value);
}
}
onClosePopup() {
this.closePopup.next();
}
After I hit Apply an event emitter is send and data is pushed in an array.
Those 2 methods: createButtons() and buildAddressPopupForm() are called in ngOnInit and the Apply button is by default disabled. I want that my button to be enabled when I change the form but I don't know how because buttons are created one time and ngOnInit is called just when the component is created. I tried with event emitter but I didn't come to a result.Any help will be apreciated, thanks
CodePudding user response:
You can achieve this with the statusChanges
Observable of your FormGroup
.
First you need to keep track of your button:
createButtons() {
// create this property in your class
this.applyButton = {
label: "apply",
id: "apply",
disabled: true,
onClick: () => this.onApplyPopup()
}
...
}
then in your ngOnInit
you subscribe to the observable and update the disabled state of your button:
ngOnInit() {
this.form.statusChanges.subscribe(status => {
if (status === 'VALID') {
this.applyButton.disabled = false;
}
});
}
CodePudding user response:
Try this way!
ngOnInit() {
this.myForm = this.formBuilder.group({
name: '',
email: '',
message: ''
});
this.onChanges();
}
onChanges(): void {
this.myForm.valueChanges.subscribe(val => {
//Do your stuff here
}