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

expert

When to use query parameters versus matrix parameters in Url?

senior

When does a lazy loaded module is loaded?

junior

What is the difference between Structural and Attribute directives in Angular?

Bình luận

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

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