码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular Directive] Implement Structural Directive Data Binding with Context in Angular

时间:2017-01-16 21:07:42      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:eem   rand   private   context   ber   text   stat   str   binding   

Just like in *ngFor, you‘re able to pass in data into your own structural directives. This is done by declaring the variable using a let statement then passing context into the createEmbeddedView call.

 

We know *ngFor we did like this:

*ngFor="let message of messages"

 

So how can we also do like this?

Remember that 

<h1 *three="let messages"> 

<!-- Equal to --> 

<template let-messages></template>

 

import {Directive, Input, TemplateRef, ViewContainerRef} from "@angular/core";
@Directive({
  selector: ‘[three]‘
})
export class ThreeDirective {
  @Input() set three(value) {
    let num = 3;

    while (num--) {
      const message = {
        to: "People" + Math.random(),
        message: "Hello" + Math.random()
      };
      this.view.createEmbeddedView(this.template, {
        $implicit: message
      })
    }
  }

  constructor(private template: TemplateRef<any>, private view: ViewContainerRef) {

  }
}

There to avoid change detection problem (value changed after compoennt inited). We need to point out after ‘three‘ as an input.

 

<h2 *three="let message">{{message.to}} - {{message.message}}</h2>

 

[Angular Directive] Implement Structural Directive Data Binding with Context in Angular

标签:eem   rand   private   context   ber   text   stat   str   binding   

原文地址:http://www.cnblogs.com/Answer1215/p/6290808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!