How to use form field Angular

Create angular project

To create an Angular project, follow these steps:

1. Install Node.js: Angular requires Node.js and npm (Node Package Manager) to be installed on your machine. Visit the official Node.js website (https://nodejs.org) and download the latest LTS version suitable for your operating system. Follow the installation instructions.

2. Install Angular CLI: Angular CLI (Command Line Interface) is a powerful tool that simplifies the process of creating and managing Angular projects. Open a terminal or command prompt and run the following command to install Angular CLI globally:


npm install -g @angular/cli

3. Create a new Angular project: Once Angular CLI is installed, you can create a new Angular project using the ng new command. Navigate to the directory where you want to create your project using the cd command, and then run the following command:

ng new my-angular-project

4. Replace my-angular-project with the name you want to give to your project. Angular CLI will generate a new project structure with all the necessary files and dependencies. Navigate to the project directory: After the project is created, navigate to the project directory using the cd command:

cd my-angular-project

5. Serve the application: To see your Angular project in action, you can use the Angular CLI's development server. Run the following command to start the server:

ng serve

This will compile the project and launch a development server. Open your web browser and visit http://localhost:4200 to see your Angular application.

Congratulations! You have successfully created an Angular project. You can now start building your application by modifying the files in the project structure, including the main HTML template (src/index.html) and the root component (src/app/app.component.ts). Refer to the official Angular documentation (https://angular.io/docs) for more information on how to work with Angular and build powerful web applications.

Angular material

1. Install required dependencies: Install the necessary dependencies for autocomplete functionality. You'll need @angular/material and @angular/cdkfor the autocomplete component. Run the following command to install them:

npm install @angular/material @angular/cdk

Style

Add this link to style css file style.css

@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";

1. Import required modules: Open the app.module.ts file located in the autocomplete folder and import the necessary modules from @angular/material and @angular/forms. Your imports should look like this:

form fields

To use form fields in Angular, you can follow these steps:

1. Start by importing the necessary modules and dependencies in your Angular component file. Typically, you'll need to import the FormsModule from @angular/forms in your module file (e.g., app.module.ts).

app.module.ts

import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatFormFieldModule } from '@angular/material/form-field'; import { AppComponent } from './app.component'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatSelectModule } from '@angular/material/select'; import { MatRadioModule } from '@angular/material/radio'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { ProfileComponent } from './profile/profile.component'; import { MatDialogModule } from '@angular/material/dialog'; import { MatDividerModule } from '@angular/material/divider'; @NgModule({ declarations: [ AppComponent, ProfileComponent ], imports: [ BrowserModule, MatCardModule, MatButtonModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, MatCheckboxModule, MatRadioModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatIconModule, MatFormFieldModule, MatInputModule, MatIconModule, MatDialogModule, MatDividerModule ], providers: [], bootstrap: [AppComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class AppModule { }

HTML file

In your component template (HTML file), you can use the Angular form fields by binding them to properties in your component class. There are various types of form fields available, such as <input>, <select>, and <textarea>. Here's an example of using an input field:

app.component.html

<div class="content" role="main"> <mat-card class="example-card"> <mat-card-header> <mat-card-title>Register</mat-card-title> <mat-card-subtitle>Please fill form</mat-card-subtitle> </mat-card-header> <mat-card-content> <br> <section> <p> <mat-form-field appearance="fill"> <mat-label>Username</mat-label> <input matInput type="text" placeholder="Placeholder" name="username" [(ngModel)]="formUser.username" #username="ngModel" required> <mat-icon matSuffix>account_circle</mat-icon> </mat-form-field> </p> <p> <mat-form-field appearance="outline"> <mat-label>Password</mat-label> <input matInput type="password" placeholder="Password" name="password" [(ngModel)]="formUser.password" #password="ngModel" required> <mat-icon matSuffix>lock</mat-icon> </mat-form-field> </p> <p> <mat-form-field appearance="fill"> <mat-label>Fullname</mat-label> <input matInput type="text" placeholder="Fullname" name="fullname" [(ngModel)]="formUser.fullname" #fullname="ngModel" required> <mat-icon matSuffix>perm_identity</mat-icon> </mat-form-field> </p> <p> <mat-form-field appearance="fill"> <mat-label>Email</mat-label> <input matInput type="email" placeholder="Email" name="email" [(ngModel)]="formUser.email" #email="ngModel" required> <mat-icon matSuffix>payment</mat-icon> </mat-form-field> </p> <p> <mat-form-field> <mat-label>About yourself</mat-label> <textarea matInput type="text" placeholder="Message" name="message" [(ngModel)]="formUser.message" #message="ngModel" required></textarea> <mat-icon matSuffix>note_add</mat-icon> </mat-form-field> </p> <p> <mat-radio-group [(ngModel)]="selectedGender" (change)="onSelectionChange($event)"> <mat-radio-button value="male">Male</mat-radio-button> <mat-radio-button value="female">Female</mat-radio-button> </mat-radio-group> </p> <p> <mat-checkbox #c (change)="isAgree(c.checked)">I agree</mat-checkbox> </p> </section> </mat-card-content> <mat-card-actions> <button mat-raised-button color="primary" (click)="onSubmit()">Send data</button> </mat-card-actions> </mat-card> </div>

In the above code, [(ngModel)] is a two-way data binding directive that allows you to bind the value of the input field to a property (name) in your component class.

1. In your component class (TypeScript file), define the property (name in this example) that you want to bind to the form field. This property will hold the value entered by the user.

You can also handle form submissions and perform actions when the form is submitted. In your component class, you can define a method and bind it to the (ngSubmit) event in the form tag. Here's an example:

app.component.ts

import { Component } from '@angular/core'; import { ProfileComponent } from './profile/profile.component'; import { MatDialog } from '@angular/material/dialog'; export class User { username!: string; password!: string; fullname!: string; email!: string; message!: string; gender!: string; agree!: boolean; } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { formUser: User = new User(); selectedGender!: string; constructor(private dialog: MatDialog) { } // Function to handle selected is agree isAgree(isAgree: boolean) { this.formUser.agree = isAgree; } // Function to handle selection change onSelectionChange(event: any) { this.selectedGender = event.value; this.formUser.gender = this.selectedGender; } onSubmit(): void { console.log(this.formUser); const dialogRef = this.dialog.open(ProfileComponent, { width: '400px', data: this.formUser }); dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); }); } }

Send data

Open the dialog: To open the dialog, you can use the open method of the MatDialog service. Pass the component you want to display in the dialog as the first argument:

In the above code, ProfimeComponent is the component that will be displayed inside the dialog. You can pass optional configuration options as the second argument, such as the width and initial data for the dialog component.

Create the dialog component:
Create a new component that will be displayed inside the dialog. This component should have its own template and logic. For example:

Generate component

To generate a component in Angular, you can use the Angular CLI (Command Line Interface) tool. Here are the steps to generate a component:

1. Open a terminal or command prompt.
2. Navigate to the root directory of your Angular project.
3. Run the following command:


ng generate component profile

profile.component.ts

import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.css'] }) export class ProfileComponent { constructor( public dialogRef: MatDialogRef<ProfileComponent>, @Inject(MAT_DIALOG_DATA) public data: any ) { console.log(this.data); } onClose(): void { this.dialogRef.close('Dialog closed'); } }

MAT_DIALOG_DATA

In the above example, MAT_DIALOG_DATA is used to inject the data passed to the dialog into the component.

profile.component.html

<h1 style="margin-left: 20px;">Profle</h1> <div mat-dialog-content> <h2>Received data:</h2> <mat-list> <mat-divider></mat-divider> <mat-list-item>Username: {{data.username}}</mat-list-item> <mat-divider></mat-divider> <mat-list-item>Password: {{data.password}}</mat-list-item> <mat-divider></mat-divider> <mat-list-item>Fullname: {{data.fullname}}</mat-list-item> <mat-divider></mat-divider> <mat-list-item>Email: {{data.email}}</mat-list-item> <mat-divider></mat-divider> <mat-list-item>Gender: {{data.gender}}</mat-list-item> <mat-divider></mat-divider> <mat-list-item *ngIf="data.agree==true">Is agree: Yes</mat-list-item> <mat-list-item *ngIf="data.agree==false">Is agree: No</mat-list-item> <mat-divider></mat-divider> <mat-list-item>About me: {{data.message}}</mat-list-item> <mat-divider></mat-divider> </mat-list> </div> <div mat-dialog-actions> <button mat-raised-button style="color: #fff !important; background: #e74c3c;" (click)="onClose()">Close</button> </div>

In the onSubmit() method, you can perform any necessary actions, such as sending the form data to a server, validating the input, or updating other parts of your application.

That's a basic example of using form fields in Angular. You can extend this concept to handle more complex forms with additional fields and validation as needed.

Post a Comment

Previous Post Next Post