Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a custom structural directive selector.
Angular
@Directive({ selector: '[[1]]' })
export class HighlightDirective {}Attempts:
3 left
💡 Hint
Common Mistakes
Using a selector without square brackets.
Using a selector that is not a valid attribute name.
✗ Incorrect
The selector for a structural directive is usually a bracketed attribute name. 'highlight' is the correct attribute name here.
2fill in blank
mediumComplete the constructor to inject the TemplateRef needed for the directive.
Angular
constructor(private [1]: TemplateRef<any>) {}Attempts:
3 left
💡 Hint
Common Mistakes
Injecting ElementRef instead of TemplateRef.
Using a variable name that does not match the injected type.
✗ Incorrect
TemplateRef is injected with a variable name like 'templateRef' to access the template inside the directive.
3fill in blank
hardFix the error in the directive to properly create an embedded view.
Angular
constructor(private templateRef: TemplateRef<any>, private [1]: ViewContainerRef) {} ngOnInit() { this.[1].createEmbeddedView(this.templateRef); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong variable name that does not match the injected type.
Not injecting ViewContainerRef at all.
✗ Incorrect
The correct Angular service to create embedded views is ViewContainerRef, commonly named 'viewContainerRef'.
4fill in blank
hardFill both blanks to conditionally render the template based on the input property.
Angular
@Input() set appIf(condition: boolean) {
if (condition) {
this.[1].createEmbeddedView(this.[2]);
} else {
this.[1].clear();
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the roles of ViewContainerRef and TemplateRef.
Using incorrect variable names that do not match injected services.
✗ Incorrect
The ViewContainerRef is used to create or clear views, and TemplateRef is the template to render.
5fill in blank
hardFill all three blanks to create a structural directive that repeats a template N times.
Angular
@Input() set appRepeat(count: number) {
this.[1].clear();
for (let i = 0; i < count; i++) {
this.[2].createEmbeddedView(this.[3]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Not clearing the container before adding views.
Using wrong variable names for injected services.
✗ Incorrect
Clear the view container, then create embedded views from the template the specified number of times.
