All quizzesHard
Dynamic Components
Preview — 3 of 10 questions
How do you programmatically create and insert a component at runtime in Angular?
javascript
@Component({
selector: 'app-host',
template: `<ng-container #host></ng-container>`,
standalone: true,
})
export class HostComponent implements AfterViewInit {
@ViewChild('host', { read: ViewContainerRef }) hostRef!: ViewContainerRef;
constructor(private injector: Injector) {}
ngAfterViewInit() {
this.hostRef.clear();
const ref = this.hostRef.createComponent(AlertComponent, { injector: this.injector });
ref.instance.message = 'Dynamic alert!';
ref.instance.dismissed.subscribe(() => ref.destroy());
}
}AUsing document.createElement() and appending it to the DOM
BUsing Renderer2.createElement() and setting component metadata
CCalling ViewContainerRef.createComponent() with the component class
DInjecting ComponentFactoryResolver and calling resolveComponentFactory() (required in Angular 17+)
What is the effect of setting changeDetection: ChangeDetectionStrategy.OnPush on a component?
javascript
@Component({
selector: 'app-list-item',
template: `<p>{{ item.name }}</p>`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
})
export class ListItemComponent {
@Input() item!: { name: string };
}AAngular checks the component on every browser event regardless of inputs
BAngular runs change detection synchronously instead of asynchronously
CAngular disables change detection for this component entirely
DAngular only checks the component when its @Input() references change, an event originates from the component, or an observable marked with async emits
What is @HostBinding used for?
javascript
@Directive({
selector: '[appExpand]',
standalone: true,
})
export class ExpandDirective {
@HostBinding('class.expanded') isExpanded = false;
@HostBinding('attr.aria-expanded') get ariaExpanded() { return this.isExpanded; }
@HostListener('click')
toggle() {
this.isExpanded = !this.isExpanded;
}
}AInjecting the host component's instance into a directive
BListening to events on the host element
CBinding the component to a specific HTML tag
DBinding a property of the host element to a component/directive property
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.