Overview
The Button class creates interactive button elements with optional form validation capabilities. Buttons can execute actions, validate forms, and include custom validation logic before execution.
Inheritance
ObjectBase → NodeBase → Button
Constructor
new Button(
id: string,
placeholder: string,
action: Action,
singleLine?: boolean,
icon?: string,
disabled?: boolean,
validateForm?: boolean,
validation?: (param: ActionEvent) => boolean
)
Parameters
The unique identifier for the button node in the DOM.
The button label text to display.
The action to execute when the button is clicked.
Whether to display the button in a single line layout.
Material icon name to display in or alongside the button.
Whether the button is disabled and cannot be clicked.
Whether to validate the entire form before executing the action.
validation
(param: ActionEvent) => boolean
Custom validation function that runs before the action executes. Returns true to allow execution, false to prevent it. Defaults to () => true.
Properties
| Property | Type | Description |
|---|
id | string | The unique identifier for the node |
placeholder | string | The button label text |
type | 'button' | The node type (read-only) |
action | Action | Action[] | Action(s) to execute on click |
validateForm | boolean | Whether to validate form before execution |
validation | (param: ActionEvent) => boolean | Custom validation function |
singleLine | boolean | Whether displayed in single line layout |
icon | string | Material icon name |
disabled | boolean | Whether the button is disabled |
errorMessage | string | Error message (inherited, typically unused for buttons) |
hint | string | Hint text to display |
autoFocus | boolean | Whether to auto-focus on load |
Methods
getNativeElement()
Returns the native DOM element for this button.
getNativeElement(): HTMLElement | null
Usage Example
import { Button, Action } from '@ng-mdf/core';
// Simple button with action
const submitButton = new Button(
'submit',
'Submit Form',
new Action('click', (event) => {
console.log('Form submitted!', event);
submitFormData(event.form);
})
);
// Button with form validation
const validateButton = new Button(
'validate',
'Save Changes',
new Action('click', (event) => {
saveChanges(event.form);
}),
false,
'save',
false,
true // validateForm: validates entire form before executing action
);
// Button with custom validation
const customValidateButton = new Button(
'customValidate',
'Process Order',
new Action('click', (event) => {
processOrder(event.form);
}),
false,
'shopping_cart',
false,
false,
(event) => {
// Custom validation logic
const cartTotal = calculateTotal(event.form);
if (cartTotal < 10) {
alert('Minimum order amount is $10');
return false; // Prevent action execution
}
return true; // Allow action execution
}
);
// Button with icon
const deleteButton = new Button(
'delete',
'Delete Item',
new Action('click', (event) => {
if (confirm('Are you sure you want to delete this item?')) {
deleteItem(event.value);
}
}),
false,
'delete', // Material icon
false
);
// Disabled button (can be enabled later)
const disabledButton = new Button(
'disabled',
'Premium Feature',
new Action('click', () => {
alert('This feature is only available to premium users');
}),
false,
'star',
true // disabled
);
// Enable button programmatically
function enablePremiumFeature() {
disabledButton.disabled = false;
}
// Button with combined form validation and custom validation
const advancedButton = new Button(
'advanced',
'Complete Purchase',
new Action('click', (event) => {
completePurchase(event.form);
}),
false,
'payment',
false,
true, // validateForm: check all form fields first
(event) => {
// Additional custom validation after form validation passes
const paymentMethod = event.form.get('paymentMethod')?.value;
if (!paymentMethod) {
alert('Please select a payment method');
return false;
}
return true;
}
);
When validateForm is true, the button automatically validates all form fields before executing the action:
const validatingButton = new Button(
'validating',
'Submit',
new Action('click', (event) => {
// This code only runs if form validation passes
console.log('Form is valid!');
submitForm(event.form);
}),
false,
'check',
false,
true // Validates entire form before action execution
);
If form validation fails:
- The action will not execute
- Form fields will display error messages
- Focus will move to the first invalid field
Custom Validation
The validation function allows custom validation logic:
const customButton = new Button(
'custom',
'Submit',
new Action('click', (event) => {
submitData(event.form);
}),
false,
undefined,
false,
false, // No automatic form validation
(event) => {
// Custom validation logic
const age = event.form.get('age')?.value;
if (age < 18) {
alert('You must be 18 or older');
return false; // Prevents action execution
}
return true; // Allows action execution
}
);
Combined Validation
You can use both form validation and custom validation together:
const combinedButton = new Button(
'combined',
'Register',
new Action('click', (event) => {
registerUser(event.form);
}),
false,
'person_add',
false,
true, // First: validate all form fields
(event) => {
// Second: run custom validation after form validation passes
const password = event.form.get('password')?.value;
const confirmPassword = event.form.get('confirmPassword')?.value;
if (password !== confirmPassword) {
alert('Passwords do not match');
return false;
}
return true;
}
);
Action Events
The action receives an ActionEvent object with useful properties:
interface ActionEvent {
value: any; // Current form value
form: FormGroup; // The entire form
control: FormControl; // The specific control (for field-level actions)
event: Event; // The native DOM event
}
const eventButton = new Button(
'event',
'Log Event',
new Action('click', (actionEvent) => {
console.log('Button value:', actionEvent.value);
console.log('Form data:', actionEvent.form.value);
console.log('Native event:', actionEvent.event);
})
);
Enabling/Disabling Dynamically
const dynamicButton = new Button(
'dynamic',
'Submit',
new Action('click', (event) => {
submitForm(event.form);
}),
false,
'send',
true // Initially disabled
);
// Enable button when form is ready
function onFormReady() {
dynamicButton.disabled = false;
}
// Disable button during processing
function processForm() {
dynamicButton.disabled = true;
submitFormAsync().then(() => {
dynamicButton.disabled = false;
});
}
Loading States
Implement loading states using the disabled property and placeholder text:
const loadingButton = new Button(
'loading',
'Submit',
new Action('click', async (event) => {
// Show loading state
loadingButton.disabled = true;
loadingButton.placeholder = 'Submitting...';
try {
await submitForm(event.form);
loadingButton.placeholder = 'Success!';
} catch (error) {
loadingButton.placeholder = 'Submit';
loadingButton.disabled = false;
}
})
);
Create icon-only buttons or buttons with icons:
// Button with icon and text
const iconTextButton = new Button(
'iconText',
'Save',
new Action('click', save),
false,
'save' // Material icon
);
// Icon-only button (use empty or short placeholder)
const iconOnlyButton = new Button(
'iconOnly',
'', // Empty label for icon-only appearance
new Action('click', edit),
false,
'edit'
);
Best Practices
Clear Action Labels
Use descriptive button labels that clearly indicate the action:
// Good
const goodButton = new Button('save', 'Save Changes', saveAction);
// Avoid
const badButton = new Button('btn', 'OK', saveAction);
Appropriate Validation
Choose the right validation approach:
- Use
validateForm: true for submit buttons
- Use custom
validation for business logic
- Combine both for comprehensive validation
Prevent Double Submission
const submitButton = new Button(
'submit',
'Submit Order',
new Action('click', async (event) => {
submitButton.disabled = true; // Prevent double-click
try {
await submitOrder(event.form);
// Handle success
} catch (error) {
// Handle error
submitButton.disabled = false; // Re-enable on error
}
}),
false,
'shopping_cart',
false,
true // Validate form before submission
);
Confirmation for Destructive Actions
const deleteButton = new Button(
'delete',
'Delete Account',
new Action('click', (event) => {
deleteAccount(event.value);
}),
false,
'delete_forever',
false,
false,
(event) => {
// Custom validation with confirmation
return confirm('Are you sure you want to delete your account? This action cannot be undone.');
}
);