Skip to main content

View Containers — ViewContainerRef | ElementRef

ElementRef

  • ElementRef
<input ngModel #username>
<p>{{ username.value }}</p>

Element references inside a Component class

export declare class ElementRef<T = any> {
nativeElement: T;
constructor(nativeElement: T);
}

@Component({...})
export class AppComponent {
@ViewChild('username') input: ElementRef<HTMLInputElement>;
}
  • Will be ready on hook ngAfterViewInit

  • Podemos pegar o elemento com uma diretiva

<div appElement>
<p>Hello World!</p>
</div>

@Directive({
selector: '[appElement]',
})
export class ElementDirective {
constructor(el: ElementRef<HTMLElement>) {
console.log(el.nativeElement);
}
}

View Containers — ViewContainerRef


<button (click)="create()">Create Components</button>

<ng-container #myContainer></ng-container>
<div #anotherContainer></div>

@Component({
// ...
})
export class ViewContainerComponent {
@ViewChild('myContainer', { read: ViewContainerRef }) myContainer: ViewContainerRef;
@ViewChild('anotherContainer', { read: ViewContainerRef }) anotherContainer: ViewContainerRef;

create(): void {
this.myContainer.createComponent(SomeComponent);
this.anotherContainer.createComponent(SomeComponent);
}
}

Templates — <ng-template> — TemplateRef — Embedded Views

<button mat-raised-button color="accent" (click)="embed()">
Embed Template
</button>

<ng-container #myContainer></ng-container>

<ng-template #myTemplate>
<p>I'm an embedded view! Yay!</p>
</ng-template>

@Component({
// ...
})
export class TemplateComponent {
@ViewChild('myContainer', { read: ViewContainerRef })
container!: ViewContainerRef;

@ViewChild('myTemplate', { read: TemplateRef })
template!: TemplateRef<any>

embed(): void {
this.container.createEmbeddedView(this.template);
}
}