Angular 5 material design template for add new
Here is an example of an Angular 5 Material Design template for adding a new item:
<!-- add-new.component.html -->
<form [formGroup]="addForm" (ngSubmit)="onSubmit()">
<mat-card>
<mat-card-header>
<mat-card-title>Add New {{ entity }}</mat-card-title>
</mat-card-header>
<mat-card-content>
<mat-form-field>
<input matInput formControlName="name" placeholder="Name">
<mat-error *ngIf="addForm.get('name').invalid">Name is required</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="description" placeholder="Description">
<mat-error *ngIf="addForm.get('description').invalid">Description is required</mat-error>
</mat-form-field>
<!-- add more form fields as needed -->
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" type="submit">Add</button>
<button mat-raised-button color="accent" type="button" (click)="onCancel()">Cancel</button>
</mat-card-actions>
</mat-card>
</form>
And here is the corresponding TypeScript code:
// add-new.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-add-new',
templateUrl: './add-new.component.html',
styleUrls: ['./add-new.component.css']
})
export class AddNewComponent implements OnInit {
addForm: FormGroup;
constructor(private snackBar: MatSnackBar) { }
ngOnInit(): void {
this.addForm = new FormGroup({
name: new FormControl('', Validators.required),
description: new FormControl('', Validators.required)
});
}
onSubmit(): void {
if (this.addForm.valid) {
// call API to add new item
console.log('Adding new item:', this.addForm.value);
this.snackBar.open('Item added successfully!', 'OK', { duration: 2000 });
} else {
this.snackBar.open('Please fill out all required fields!', 'OK', { duration: 2000 });
}
}
onCancel(): void {
// reset form and close dialog
this.addForm.reset();
}
}
This template uses the mat-card
component to create a Material Design card with a header, content, and actions. The form fields are created using mat-form-field
and matInput
components. The form is validated using the Validators
class from Angular.
The onSubmit
method is called when the form is submitted, and it checks if the form is valid. If it is, it calls an API to add a new item. If not, it displays an error message using the MatSnackBar
component.
The onCancel
method is called when the user clicks the "Cancel" button, and it resets the form and closes the dialog.
You can customize this template to fit your specific needs by adding or removing form fields, modifying the validation logic, and changing the API call to add a new item.