【发布时间】:2017-12-16 17:54:26
【问题描述】:
angular2 ng-templates 中如何使用以下关键字
- angular 2 模板中
$implicit的用途是什么? -
let-<attribute>和$implicit是什么关系?
【问题讨论】:
标签: angular ng-template
angular2 ng-templates 中如何使用以下关键字
$implicit 的用途是什么? let-<attribute>和$implicit是什么关系?【问题讨论】:
标签: angular ng-template
您可以在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
另一方面,如果我们有这样的上下文:
{ bar: 'value' }
我们必须像这样声明变量:
let-foo="bar"
【讨论】:
对于多个变量,您应该执行以下操作, 一个模板是:
<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
【讨论】:
如果您只需要将变量从我们引用它的容器传递给模板,我们可以使用
<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>
【讨论】:
我使用 $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>
【讨论】: