Angular Components


What is a component in Angular?

A component in Angular is the fundamental building block of the user interface. It encapsulates the HTML, CSS, and TypeScript needed to display a part of the user interface (UI). Each Angular application consists of several components that work together to create a complete application. Components define their behavior and the data they display via properties and methods in the TypeScript class.


What are the main parts of an Angular component?

An Angular component consists of three main parts:

  • Template: The HTML view associated with the component, defining what gets rendered in the browser.
  • Class: The TypeScript code that defines the component's logic and properties, using decorators like @Component.
  • Styles: The CSS or SCSS styles that define the appearance of the component.

Example of an Angular component:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  title = 'Angular Component';
}

This example defines a simple Angular component with a title property and links to its template and style files.


What is the @Component decorator, and how is it used?

The @Component decorator is a special TypeScript decorator used to define metadata for an Angular component. It tells Angular what the component's selector, template, and styles are, and it configures the component's behavior within the Angular app.

Example of the @Component decorator:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  // Component logic here
}

In this example, the @Component decorator configures the ExampleComponent class, specifying the selector (app-example), template URL, and styles.


What is the purpose of the selector in an Angular component?

The selector in an Angular component specifies how the component is used in the HTML markup. The selector can be a tag, an attribute, a class, or even a combination. It allows the component to be instantiated in the HTML template of other components or in the main app template.

Example of a component with a selector:

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html'
})
export class HelloComponent {
  message = 'Hello, Angular!';
}

In the HTML file, the component can be used as follows:

<app-hello></app-hello>

In this example, the <app-hello> tag is the custom element created by the HelloComponent and is used to render the component's content in the view.


How do you pass data between components in Angular?

Data can be passed between components in Angular using component inputs (for parent-to-child communication) and outputs (for child-to-parent communication):

  • @Input: Used to pass data from a parent component to a child component.
  • @Output: Used to emit events from a child component to the parent component.

Example of @Input and @Output:

@Component({
  selector: 'app-child',
  template: '<button (click)="notifyParent()">Click me</button>'
})
export class ChildComponent {
  @Input() childMessage: string;
  @Output() messageEvent = new EventEmitter<string>();

  notifyParent() {
    this.messageEvent.emit('Hello from Child');
  }
}

@Component({
  selector: 'app-parent',
  template: `
    <app-child [childMessage]="parentMessage" (messageEvent)="receiveMessage($event)"></app-child>
    <p>Message from child: {{message}}</p>
  `
})
export class ParentComponent {
  parentMessage = 'Message from Parent';
  message: string;

  receiveMessage(event: string) {
    this.message = event;
  }
}

In this example, parentMessage is passed from the parent component to the child component using @Input, and messageEvent is emitted by the child component to the parent using @Output.


What is the difference between inline and external templates in Angular components?

In Angular, templates can be defined either inline or in external files:

  • Inline template: The HTML is defined directly in the @Component decorator using the template property. This is useful for simple components with small templates.
  • External template: The HTML is placed in a separate file, and the path to the file is specified using the templateUrl property. This is better suited for larger, more complex components.

Example of an inline template:

@Component({
  selector: 'app-inline',
  template: '<p>This is an inline template!</p>'
})
export class InlineComponent {}

Example of an external template:

@Component({
  selector: 'app-external',
  templateUrl: './external.component.html'
})
export class ExternalComponent {}

In this case, the template is stored in external.component.html for easier management.


How do you style Angular components?

Angular components can be styled using the styleUrls property to link to external stylesheets or the styles property for inline styles. Angular also supports scoped styles, meaning styles defined for a component are applied only to that component and not globally.

Example of component styling:

@Component({
  selector: 'app-styled',
  templateUrl: './styled.component.html',
  styleUrls: ['./styled.component.css']
})
export class StyledComponent {}

In styled.component.css:

p {
  color: blue;
}

The CSS defined in styled.component.css will only apply to this component, ensuring style encapsulation.


What are lifecycle hooks in Angular components?

Angular lifecycle hooks are special methods that provide visibility into key moments in the lifecycle of a component. These hooks allow developers to execute custom logic at various stages, such as when a component is initialized, when it receives new data, or when it is destroyed.

Common lifecycle hooks include:

  • ngOnInit: Called once after the component's initialization. It is commonly used for initializing data or setting up subscriptions.
  • ngOnChanges: Called whenever input properties of the component change.
  • ngOnDestroy: Called just before the component is destroyed. It is used for cleanup operations, such as unsubscribing from observables.

Example of lifecycle hooks:

@Component({
  selector: 'app-lifecycle',
  templateUrl: './lifecycle.component.html'
})
export class LifecycleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component initialized');
  }

  ngOnDestroy() {
    console.log('Component destroyed');
  }
}

In this example, ngOnInit is called when the component is initialized, and ngOnDestroy is called when the component is about to be destroyed.


What is ngOnInit and when is it used?

ngOnInit is a lifecycle hook in Angular that is called once after the component's inputs have been initialized. It is commonly used to initialize data, make HTTP requests, or perform any setup logic needed for the component.

Example of using ngOnInit:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent implements OnInit {
  data: any;

  ngOnInit() {
    this.data = 'Component Initialized!';
    console.log(this.data);
  }
}

In this example, the ngOnInit hook is used to initialize the data property when the component is created.


What is component encapsulation in Angular?

Component encapsulation in Angular controls how styles defined in a component's stylesheet affect the component's HTML and how they interact with the global styles. Angular provides three encapsulation modes:

  • Emulated: (default) Emulates Shadow DOM by scoping styles to the component, ensuring styles don't affect other components.
  • None: No encapsulation; styles are global and affect other components.
  • ShadowDom: Uses the native Shadow DOM, which is a browser feature that fully encapsulates the component's styles.

Example of setting encapsulation:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  encapsulation: ViewEncapsulation.Emulated
})
export class ExampleComponent {}

In this example, the component uses the default ViewEncapsulation.Emulated mode to scope its styles.

Ads