typescript ElementRef,TemplateRef,ViewContainerRef

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript ElementRef,TemplateRef,ViewContainerRef相关的知识,希望对你有一定的参考价值。

// ElementRef
// <span #spanRef>I am span</span>

@ViewChild("spanRef") spanRef: ElementRef;

ngAfterViewInit(): void {
        // outputs `I am span`
        console.log(this.spanRef.nativeElement.textContent);
}

// This is the most basic abstraction. If you observe it’s class structure, you’ll see that it only holds 
// the native element it’s associated with. It’s useful for accessing native DOM element.

// However, such usage is discouraged by Angular team. Not only it poses security risk, but it also creates
// tight coupling between your application and rendering layers which makes is difficult to run an app
// on multiple platforms

// ElementRef can be returned for any DOM element using ViewChild decorator.



// TemplateRef

/* <ng-template #tpl>
            <span>I am span in template</span>
    </ng-template>
*/
@ViewChild("tpl") tpl: TemplateRef<any>;



// ViewContainerRef
// Represents a container where one or more views can be attached.

// The first thing to mention here is that any DOM element can be used as a view container.
// What’s interesting is that Angular doesn’t insert views inside the element, but appends them after
// the element bound to ViewContainer. This is similar to how router-outlet inserts components.

/*
    <span>I am first span</span>
        <ng-container #vc></ng-container>
        <span>I am last span</span>
        <ng-template #tpl>
            <span>I am span in template</span>
        </ng-template>
*/
@ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;
@ViewChild("tpl") tpl: TemplateRef<any>;

ngAfterViewInit() {
        let view = this.tpl.createEmbeddedView(null);
        this.vc.insert(view);
}

// ViewContainer also provides API to create a view automatically:

this.vc.createEmbeddedView(this.tpl)

// ngTemplateOutlet is further a shortcut 
/*
        <span>I am first span</span>
        <ng-container [ngTemplateOutlet]="tpl"></ng-container>
        <span>I am last span</span>
        <ng-template #tpl>
            <span>I am span in template</span>
        </ng-template>
*/

以上是关于typescript ElementRef,TemplateRef,ViewContainerRef的主要内容,如果未能解决你的问题,请参考以下文章

typescript ElementRef,TemplateRef,ViewContainerRef

Typescript零碎总结

处理用 TypeScript 编写的 React 功能组件中的 Ref:Element is not assignable 错误

类型“ElementRef”不是通用的

angular 2 - 在 elementRef 上设置选择

ElementRef, @ViewChild & Renderer