Using Input Elements
Adding Text Input
Modify the src/app/app.component.html
file:
<label for="username">Username:</label>
<input type="text" id="username" [(ngModel)]="username" />
<p>Entered Username: {{ username }}</p>
In src/app/app.component.ts
:
username: string = '';
Using Combo Box (Dropdown)
Adding a Combo Box
<label for="color">Choose a color:</label>
<select id="color" [(ngModel)]="selectedColor">
<option *ngFor="let color of colors" [value]="color">{{ color }}</option>
</select>
<p>Selected Color: {{ selectedColor }}</p>
In src/app/app.component.ts
:
colors = ['Red', 'Green', 'Blue', 'Yellow'];
selectedColor: string = '';
Using Checkboxes
Adding a Checkbox
<label>
<input type="checkbox" [(ngModel)]="isSubscribed" /> Subscribe to Newsletter
</label>
<p>Subscription Status: {{ isSubscribed ? 'Subscribed' : 'Not Subscribed' }}</p>
In src/app/app.component.ts
:
isSubscribed: boolean = false;
Using Option Buttons (Radio Buttons)
Adding Radio Buttons
<p>Choose your gender:</p>
<label>
<input type="radio" name="gender" value="Male" [(ngModel)]="gender" /> Male
</label>
<label>
<input type="radio" name="gender" value="Female" [(ngModel)]="gender" /> Female
</label>
<p>Selected Gender: {{ gender }}</p>
In src/app/app.component.ts
:
gender: string = '';
Using Tables
Displaying a Static Table
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>25</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td>30</td>
</tr>
</tbody>
</table>
Dynamic Table with Angular
In app.component.ts
:
people = [
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 },
{ id: 3, name: 'Mike', age: 35 }
];
In app.component.html
:
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of people">
<td>{{ person.id }}</td>
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
</tbody>
</table>
Using Buttons
Adding a Button and Handling Click Events
In app.component.ts
:
clickCount: number = 0;
incrementClickCount() {
this.clickCount++;
}
In app.component.html
:
<p>Button clicked {{ clickCount }} times.</p>
<button (click)="incrementClickCount()">Click Me</button>
Pingback: What Is Angular - Tech Mentor