【问题标题】:What is $implicit in angular 2?角度 2 中的 $implicit 是什么?
【发布时间】:2017-12-16 17:54:26
【问题描述】:

angular2 ng-templates 中如何使用以下关键字

  • angular 2 模板中$implicit 的用途是什么?
  • let-<attribute>$implicit是什么关系?

【问题讨论】:

    标签: angular ng-template


    【解决方案1】:

    您可以在ng-templatelet-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 Example

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

    { bar: 'value' }
    

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

    let-foo="bar"
    

    【讨论】:

    • 有没有办法声明多个变量并使用它们?
    • 谢谢,@yurzui 很好的解释清除了我所有的疑惑:)
    • 非常感谢您的解释,非常完美,非常好。
    【解决方案2】:

    对于多个变量,您应该执行以下操作, 一个模板是:

    <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
    

    【讨论】:

      【解决方案3】:

      如果您只需要将变量从我们引用它的容器传递给模板,我们可以使用

      <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>
        

        【讨论】:

          猜你喜欢
          • 2018-07-11
          • 2016-02-19
          • 2016-08-23
          • 2020-02-26
          • 1970-01-01
          • 1970-01-01
          • 2020-06-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多