以下关键词在Angular2的ng-template中如何使用?
$implicit
在angular 2模板中的目的是什么?let-<attribute>
和$implicit
之间有什么关系?
以下关键词在Angular2的ng-template中如何使用?
$implicit
在angular 2模板中的目的是什么?let-<attribute>
和 $implicit
之间有什么关系?通过在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>