Angular components and templates form the building blocks of Angular applications. Below is a comprehensive list of questions with detailed answers, examples, and implementation steps.
1. What is a component in Angular?
Answer
A component is a fundamental building block of Angular applications that controls a part of the user interface. It consists of:
- A TypeScript class to handle logic and data.
- An HTML template for the view.
- CSS or SCSS for styling.
Example
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: '<h1>Hello, {{name}}!</h1>',
styles: ['h1 { color: blue; }']
})
export class ExampleComponent {
name = 'Angular';
}
Steps to Implement
- Use Angular CLI to generate a component:
ng generate component component-name. - Define the logic in the TypeScript class.
- Create the view in the HTML file.
- Add styles in the CSS or SCSS file.
- Include the component in the parent module.
2. What is the purpose of the @Component decorator?
Answer
The @Component decorator is used to define metadata for an Angular component. It specifies the selector, template, styles, and other configurations.
Example
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
Steps to Implement
- Add the
@Componentdecorator above the class. - Define properties like
selector,template, andstyles. - Use the selector in HTML to render the component.
3. What is data binding in Angular? Explain its types.
Answer
Data binding connects the UI (view) and the business logic (component). Angular supports four types:
- Interpolation: Displays data from the component in the template.
<h1>{{title}}</h1> - Property Binding: Sets properties of HTML elements.
<input [value]="title"> - Event Binding: Responds to user actions.
<button (click)="onClick()">Click Me</button> - Two-Way Binding: Combines property and event binding.
<input [(ngModel)]="title">
Example
export class AppComponent {
title = 'Angular';
onClick() {
this.title = 'Button Clicked!';
}
}
4. How do you create a component in Angular?
Answer
Components can be created manually or using Angular CLI.
Steps to Implement
- Run the command:
ng generate component component-name. - Angular generates the files:
.ts,.html,.css, and.spec.ts. - Include the component in the
declarationsarray of the module. - Use the component’s selector in the parent component.
5. What is a template in Angular?
Answer
A template is HTML code combined with Angular’s directives and bindings to render the view.
Example
<div>
<h1>{{title}}</h1>
<button (click)="changeTitle()">Change Title</button>
</div>
6. What is the difference between property binding and attribute binding?
Answer
- Property Binding: Binds to DOM properties, enabling dynamic updates.
<input [value]="username"> - Attribute Binding: Binds to HTML attributes, typically static.
<button [attr.aria-label]="label">Click Me</button>
7. What is interpolation in Angular?
Answer
Interpolation is a type of data binding that embeds data from the component into the HTML template using {{}}.
Example
<p>{{message}}</p>
Steps to Implement
- Define a property in the component class.
- Use
{{propertyName}}in the HTML template.
8. How do you use ng-content in Angular?
Answer
The ng-content directive is used to project content from a parent component into a child component.
Example
<!-- Parent Component --> <app-child> <p>Content to project</p> </app-child> <!-- Child Component Template --> <ng-content></ng-content>
9. What are Angular lifecycle hooks?
Answer
Lifecycle hooks are methods that Angular calls at specific stages of a component’s lifecycle.
Key Hooks
ngOnInit: Initializes data.ngOnChanges: Responds to input changes.ngOnDestroy: Cleans up resources.
Example
ngOnInit() {
console.log('Component initialized');
}
10. How do you create dynamic components in Angular?
Answer
Dynamic components are created programmatically using the ViewContainerRef and ComponentFactoryResolver.
Example
constructor(private resolver: ComponentFactoryResolver, private container: ViewContainerRef) {}
loadComponent(component: Type<any>) {
const factory = this.resolver.resolveComponentFactory(component);
this.container.createComponent(factory);
}
11. What are Angular structural directives?
Answer
Structural directives alter the DOM layout by adding or removing elements. Examples include *ngIf, *ngFor, and *ngSwitch.
Example
<div *ngIf="isVisible">Visible Content</div>
<ul>
<li *ngFor="let item of items">{{item}}</li>
</ul>
12. How does the *ngIf directive work?
Answer
The *ngIf directive conditionally includes or excludes an element from the DOM based on a boolean expression.
Example
<div *ngIf="isLoggedIn">Welcome, User!</div>
13. What is the purpose of *ngFor?
Answer
The *ngFor directive is used to iterate over a collection and display its items in the template.
Example
<ul>
<li *ngFor="let user of users">{{user.name}}</li>
</ul>
14. How do you use @Input and @Output?
Answer
@Input: Passes data from a parent to a child component.@Output: Sends events from a child to a parent component.
Example
@Input() userName: string; @Output() userUpdated = new EventEmitter<string>();
15. How do you use pipes in Angular templates?
Answer
Pipes transform template data. For example, the uppercase pipe converts text to uppercase.
Example
<p>{{name | uppercase}}</p>
16. How do you apply styles dynamically in Angular?
Answer
Use [ngStyle] or [ngClass] for dynamic styling.
Example
<div [ngStyle]="{color: 'red'}">Styled Text</div>
17. How do you handle events in Angular templates?
Answer
Use event binding syntax (eventName)="methodName()".
Example
<button (click)="onClick()">Click Me</button>
18. How do you use template reference variables?
Answer
Template reference variables provide access to DOM elements in the template.
Example
<input #inputRef> <button (click)="log(inputRef.value)">Log Input</button>
19. How do you use child components in Angular?
Answer
Include the child component selector in the parent template.
Example
<app-child></app-child>
20. How do you project multiple content slots using ng-content?
Answer
Use select attribute in ng-content for multiple slots.
Example
<ng-content select="header"></ng-content> <ng-content select="footer"></ng-content>