TemplateRef需要类型参数

bvd*_*vdb 10 angular

组件HTML:

<ng-template #content/> </ng-template>
Run Code Online (Sandbox Code Playgroud)

组件TS:

@ViewChild('content')
public content: TemplateRef;
Run Code Online (Sandbox Code Playgroud)

Visual Studio消息:

[ts] Generic type 'TemplateRef<C>' requires 1 type argument(s)
Run Code Online (Sandbox Code Playgroud)

我应该做到TemplateRef<any>吗?代码示例似乎永远不会指定泛型. 这是新的吗?

Gün*_*uer 10

在他们使用的Angular Material 2中

TemplateRef<any>
Run Code Online (Sandbox Code Playgroud)

无处不在 https://github.com/angular/material2/search?utf8=%E2%9C%93&q=templateref&type=

我还没有看到任何与此类型参数相关的内容.


vhb*_*zan 7

如果您想使用 Angular 最佳实践,并且在传递对 HTML 元素的引用时不使用“ any”作为类型,TemplateRef<C>您可以使用 html 元素的通用接口类型:Element

组件 TS:

public content: TemplateRef<Element>;
Run Code Online (Sandbox Code Playgroud)


She*_*eed 6

基于 Nexaddo 的帖子,我将在这里详细说明。给定一个组件:

    @Component({
      selector: 'app-modal',
      templateUrl: './my.component.html',
      styleUrls: ['./my.component.css']
    })
    export class MyComponent implements OnInit {
      data = "oldData";
      @ViewChild() template0:TemplateRef<any>;
      constructor() { }
    
      ngOnInit() {
      }
    
    }
Run Code Online (Sandbox Code Playgroud)

TempalteRef 顾名思义是一个模板引用。@ViewChild()只是在那里说“模板在我的视图中”,您可以使用@ContentChild()或者@Input()如果您将模板从调用传递给 MyComponent。

当您在组件模板中调用它时(此处为./my.component.html),在大多数情况下您会这样做:

    <ng-template #template0>
        <p>Lorem Ipsum...</p>
        <p>{{data}}</p>
        <p>Lorem Ipsum...</p>
    </ng-template>
    <ng-container *ngTemplateOutlet="template0">
        
    </ng-container>
Run Code Online (Sandbox Code Playgroud)

在这里,对template0的调用将从组件上下文中插入数据,因为其中的所有模板共享相同的上下文。但你可以指定另一个上下文,如下所示:

    <ng-container *ngTemplateOutlet="template0;context=newCtx">
        
    </ng-container>
Run Code Online (Sandbox Code Playgroud)

从:

    export class MyComponent implements OnInit {
      data = "oldData";
      newCtx = {data = "newData"};
      ...
    }
Run Code Online (Sandbox Code Playgroud)

像这样,“newData”将被插值而不是“oldData”。

现在,您确实意识到newCtx作为any一种类型,这就是它的TemplateRef<any>来源。在大多数情况下,您可能对此感到满意,但为了可重用性或只是为了编译器检查,您可以精确确定该上下文应该是哪个类:TemplateRef<CustomContextClass>,并且您必须像这样声明您的上下文:(newCtx:CustomContextClass或任何子类自然是 CustomContextClass 的)。

src:https: //blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/https://blog.mgechev.com/2017/10/01/angular-template-ref-dynamic -范围自定义模板/


Nex*_*ddo 5

您可以使用,TempalteRef<any>并且在几乎所有用例中您都会没事的。

但是,如果你想了解更多信息,你可以阅读这篇博客 (特别是“动态范围角”部分中)Minko Gechev