在Angular 2中,$implicit是什么?

74

以下关键词在Angular2的ng-template中如何使用?

  • $implicit 在angular 2模板中的目的是什么?
  • let-<attribute>$implicit 之间有什么关系?
4个回答

104

通过在ng-template上使用let-name,您可以定义局部变量。

当Angular调用createEmbeddedView创建模板时,它还可以传递将在ng-template内使用的上下文。

在上下文对象中使用键$implicit会将其值设置为默认值。因此,如果我们编写:

vcRef.createEmbeddedView(template, { $implicit: 'value' })

我们有模板

<ng-template let-foo> 
 {{ foo }}
</ng-template>

那么我们可以这样考虑

<ng-template let-foo="$implicit"> 
  {{ foo }}
</ng-template>

所以foo将等于value

Plunker示例

另一方面,如果我们有这样的上下文:

{ bar: 'value' }

我们必须像这样声明变量:

let-foo="bar"

2
有没有办法声明多个变量并使用它们? - Mantu Nigam
谢谢,@yurzui非常好的解释,消除了我所有的疑虑 :) - Mantu Nigam
非常感谢您的解释,非常完美,非常好。 - Hoiama Rodrigues

22

对于多个变量,你应该像下面这样操作, 一个模板可能是:

<ng-template [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{$implicit: 'Hello', key2: 'value2', key3: 'value3'}"> </ng-template>

然后

<ng-template #template let-default let-key2="key2" let-key3="key3">
{{default}}
{{key2}}
{{key3}}
</ng-template>
所以,输出将是,
default = Hello
key2 = value2
key3 = value3

6
如果我们想从容器中只传递一个变量到模板中,我们可以使用以下方法:
<ng-container *ngTemplateOutlet="deleteClient;context: firstName">
</ng-container>

使用方法如下。

<ng-template #deleteClient let-client="firstName">
Are you sure? Want to remove {{ client }} !
</ng-template>

如果必须将对象本身传递给模板,我们可以使用:
<ng-container *ngTemplateOutlet="deleteClient;context: { $implicit: client }"> 
</ng-container>

并且这样使用它。

<ng-template #deleteClient let-client>
Are you sure? Want to remove {{ client.firstName }} {{ client.lastName }}!
</ng-template>

4

我已经使用$implicit将值传递给ng-template,在动态创建标题的锚标签。 $implicit用于向ng-template传递数据。

<ng-container [ngTemplateOutlet]=" col.bodyTemplate"
                        [ngTemplateOutletContext]="{$implicit: product}">
 </ng-container>

<ng-template #productTitle let-product> // let-product-> declaring local variable
    <a [routerLink]="['/products', product.Id]" [queryParams]="{searchText:searchText}">
        {{product.Title}}</a>
</ng-template>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接