【问题标题】:TemplateRef requires type argumentTemplateRef 需要类型参数
【发布时间】:2018-02-09 03:20:04
【问题描述】:

组件 HTML:

<ng-template #content/> </ng-template>

组件 TS:

@ViewChild('content')
public content: TemplateRef;

Visual Studio 消息:

[ts] Generic type 'TemplateRef<C>' requires 1 type argument(s)

我应该只是让它TemplateRef&lt;any&gt; 吗? 不过,代码示例似乎从未指定泛型。 这是新的吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    他们在 Angular Material 2 中使用

    TemplateRef<any>
    

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

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

    【讨论】:

    • 这并没有解释,为什么泛型首先退出?
    【解决方案2】:

    您可以使用TempalteRef&lt;any&gt;,几乎在所有用例中都可以。

    但如果您想了解更多信息,可以阅读this blog post (特别是“Angular 中的动态范围” 部分) Minko Gechev

    【讨论】:

    • 这个答案需要选择@bvdb,但它缺乏解释,只是指出一篇文章。
    【解决方案3】:

    基于 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() {
          }
        
        }
    

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

    当你在你的组件模板中调用它时(./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>
    

    这里,对 template0 的调用将从组件上下文中插入 data,因为其中的所有模板共享相同的上下文。但是您可以像这样指定另一个上下文

        <ng-container *ngTemplateOutlet="template0;context=newCtx">
            
        </ng-container>
    

    发件人:

        export class MyComponent implements OnInit {
          data = "oldData";
          newCtx = {data = "newData"};
          ...
        }
    

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

    现在,您确实意识到 newCtx 具有 any 作为类型,这就是 TemplateRef&lt;any&gt; 的来源。在大多数情况下,你可能会觉得它没问题,但为了可重用性或只是为了编译器检查,你可以明确这个上下文应该是哪个类:TemplateRef&lt;CustomContextClass&gt;,你必须像这样声明你的上下文:@987654333 @(当然也可以是 CustomContextClass 的任何子类)。

    src:https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/https://blog.mgechev.com/2017/10/01/angular-template-ref-dynamic-scoping-custom-templates/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多