1. Component Interaction: Parent-Child Communication
Angular provides robust mechanisms for parent-child component interaction. This is crucial for building modular and maintainable UIs. Parent-child communication can be achieved using Input and Output decorators.
2. Input and Output Decorators
Using @Input
The @Input
decorator allows a parent component to pass data to its child component.
For example:
// Parent component template
// Child component
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '{{ data }}
'
})
export class ChildComponent {
@Input() data!: string;
}
Using @Output
The @Output
decorator allows the child component to emit events to the parent component.
For example:
// Child component
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ''
})
export class ChildComponent {
@Output() message = new EventEmitter();
sendMessage() {
this.message.emit('Hello from Child!');
}
}
// Parent component template
3. Dynamic Components
Angular supports dynamic component creation at runtime using the ComponentFactoryResolver
or the newer
ViewContainerRef
approach.
import { Component, ComponentRef, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-dynamic',
template: ' '
})
export class DynamicComponent {
@ViewChild('container', { read: ViewContainerRef }) container!: ViewContainerRef;
loadComponent() {
this.container.clear();
const componentRef: ComponentRef = this.container.createComponent(SomeComponent);
componentRef.instance.data = 'Dynamic Data';
}
}
4. ViewChild and ContentChild
Using @ViewChild
@ViewChild
gives access to a child component or DOM element in the same template.
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'app-parent',
template: ' '
})
export class ParentComponent {
@ViewChild('child') child!: ChildComponent;
ngAfterViewInit() {
console.log(this.child.someMethod());
}
}
Using @ContentChild
@ContentChild
allows access to a child projected into the component via ng-content
.
import { Component, ContentChild } from '@angular/core';
@Component({
selector: 'app-wrapper',
template: ' '
})
export class WrapperComponent {
@ContentChild('projectedChild') child!: any;
ngAfterContentInit() {
console.log(this.child);
}
}
0 Comments