Angular Unit 1 QB Sol
Angular Unit 1 QB Sol
```html
<div *ngIf="showElement">
This element will be displayed if showElement is true.
</div>
```
```html
<ul>
<li *ngFor="let item of items">
{{ item }}
</li>
</ul>
```
```html
<div [ngSwitch]="value">
<div *ngSwitchCase="'a'">Value is 'a'</div>
<div *ngSwitchCase="'b'">Value is 'b'</div>
<div *ngSwitchDefault>Value is neither 'a' nor 'b'</div>
</div>
```
```html
<div [ngClass]="{ 'active': isActive, 'disabled': isDisabled }">
This div has dynamic CSS classes.
</div>
```
```html
<div [ngStyle]="{ 'color': isActive ? 'green' : 'red', 'font-size.px':
fontSize }">
This div has dynamic styles.
</div>
```
```html
<input type="text" [(ngModel)]="name">
```
1. Interpolation (`{{}}`)
2. Property binding (`[]`)
3. Event binding (`()`)
4. Two-way binding (`[()]`)
Here's how you can implement each type of data binding:
```html
<p>{{ message }}</p>
```
```html
<img [src]="imageUrl">
```
**3. Event Binding (`()`):**
```html
<button (click)="handleClick()">Click Me</button>
```
```html
<input [(ngModel)]="name">
```
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<h1>{{ title }}</h1>
<input [(ngModel)]="name" placeholder="Enter your name">
<p>Hello, {{ name }}</p>
<button (click)="changeMessage()">Change Message</button>
<p>{{ message }}</p>
`,
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
title = 'Data Binding Example';
name = '';
message = 'Initial Message';
changeMessage() {
this.message = 'New Message';
}
}
```
**Example:**
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<div *ngIf="isLoggedIn; else loginTemplate">
<h2>Welcome, {{ username }}!</h2>
<button (click)="logout()">Logout</button>
</div>
<ng-template #loginTemplate>
<h2>Login</h2>
<input type="text" placeholder="Username"
[(ngModel)]="username">
<input type="password" placeholder="Password"
[(ngModel)]="password">
<button (click)="login()">Login</button>
</ng-template>
`
})
export class ExampleComponent {
isLoggedIn = false;
username: string = '';
password: string = '';
login() {
// Logic for login
this.isLoggedIn = true;
}
logout() {
// Logic for logout
this.isLoggedIn = false;
this.username = '';
this.password = '';
}
}
```
In this example: