Angular Formly provides many built-in field types. Let's explore the most commonly used ones and how to configure them.
Common Field Types
Here are the most frequently used field types with examples:
field-types.example.ts
fields: FormlyFieldConfig[] = [
// Text Input
{
key: 'firstName',
type: 'input',
templateOptions: {
label: 'First Name',
placeholder: 'Enter first name',
required: true
}
},
// Email Input
{
key: 'email',
type: 'input',
templateOptions: {
label: 'Email',
type: 'email',
required: true
}
},
// Password Input
{
key: 'password',
type: 'input',
templateOptions: {
label: 'Password',
type: 'password',
required: true,
minLength: 8
}
},
// Textarea
{
key: 'description',
type: 'textarea',
templateOptions: {
label: 'Description',
rows: 3,
placeholder: 'Enter description'
}
},
// Select Dropdown
{
key: 'country',
type: 'select',
templateOptions: {
label: 'Country',
options: [
{ value: 'us', label: 'United States' },
{ value: 'uk', label: 'United Kingdom' },
{ value: 'ca', label: 'Canada' }
],
required: true
}
},
// Checkbox
{
key: 'terms',
type: 'checkbox',
templateOptions: {
label: 'I agree to the terms and conditions',
required: true
}
},
// Radio Buttons
{
key: 'gender',
type: 'radio',
templateOptions: {
label: 'Gender',
options: [
{ value: 'male', label: 'Male' },
{ value: 'female', label: 'Female' },
{ value: 'other', label: 'Other' }
]
}
}
];
Advanced Field Configuration
You can also use advanced features like conditional fields and expressions:
advanced-fields.example.ts
fields: FormlyFieldConfig[] = [
{
key: 'hasAccount',
type: 'checkbox',
templateOptions: {
label: 'I already have an account'
}
},
{
key: 'username',
type: 'input',
templateOptions: {
label: 'Username',
required: true
},
// Show only if hasAccount is true
hideExpression: '!model.hasAccount'
},
{
key: 'email',
type: 'input',
templateOptions: {
label: 'Email',
type: 'email',
required: true
},
// Show only if hasAccount is false
hideExpression: 'model.hasAccount'
}
];
⚠️ Important
Always use the key property to specify the field name. This is how Formly maps the field to your model object.