Câu hỏi phỏng vấn Angular
Câu hỏi

How would you insert an embedded ...

Câu trả lời

To insert an embedded view from a prepared TemplateRef in Angular, you would typically follow these steps:

  1. Obtain a Reference to TemplateRef: First, you need to have a TemplateRef instance that represents the template you want to render. This is usually obtained using Angular's ViewChild decorator to access the template within your component's class. For example:

    @ViewChild('templateRef', { static: true, read: TemplateRef })
    private templateRef: TemplateRef<any>;

    Here, templateRef is a template reference variable defined in your component's template.

  2. Access ViewContainerRef: Next, you need a ViewContainerRef to define the location in the view where the template will be rendered. This can also be obtained using the ViewChild decorator:

    @ViewChild('viewContainerRef', { read: ViewContainerRef })
    private viewContainerRef: ViewContainerRef;

    viewContainerRef is typically a reference to an ng-container or any other container element in your component's template.

  3. Create and Insert the Embedded View: With both TemplateRef and ViewContainerRef available, you can now create an embedded view and insert it into the view container using the createEmbeddedView method:

    this.viewContainerRef.createEmbeddedView(this.templateRef);

    This method instantiates the template referenced by TemplateRef and inserts the resulting view into the container specified by ViewContainerRef.

Example

Here's a complete example of how you might set up your component:

import { Component, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <ng-template #templateRef>
      <p>Hello, Embedded View!</p>
    </ng-template>
    <ng-container #viewContainerRef></ng-container>
  `
})
export class ExampleComponent {
 ...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What is Redux and how does it relate to an Angular app?

middle

What is the purpose of Wildcard route?

middle

What are the ways to control AOT compilation?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào