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:

    typescript Copy
    @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:

    typescript Copy
    @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:

    typescript Copy
    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:

typescript Copy
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

junior

What is a Service, and when will you use it?

middle

Explain the difference between Promise and Observable in Angular?

senior

Why would you use renderer methods instead of using native element methods?

Bình luận

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

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