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

[Angular Directive] Assign a Structual Directive a Dynamic Context in Angular 2

时间:2017-01-16 21:00:26      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:nbsp   pass   ati   tor   struct   math   exp   custom   under   

 Just like passing in an array to *ngFor, you can pass in any value into your structural directive so that it can render templates based on those values. It‘s crucial to understand how the *directive syntax expands into a <template> and adds a custom @Input based on the syntax you use so that you can use your own data.
 
 
The syntax looks like:
<h2 *three="let message from messages">{{message.to}} - {{message.message}}</h2>

 

For template it would looks like:

<template [threeFrom]="messages"></template>

It combimes ‘three‘ and ‘from‘ keywords.

 

So the directive would looks like:

import {Directive, Input, TemplateRef, ViewContainerRef} from "@angular/core";
@Directive({
  selector: ‘[three]‘
})
export class ThreeDirective {
  @Input() set threeFrom({one, two, three}) {this.view.createEmbeddedView(this.template, {
      $implicit: {
        to: "People" + Math.random(),
        message: two
      }
    });

    this.view.createEmbeddedView(this.template, {
      $implicit: {
        to: "People" + Math.random(),
        message: three
      }
    });

    this.view.createEmbeddedView(this.template, {
      $implicit: {
        to: "People" + Math.random(),
        message: one
      }
    });
  }

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

  }
}

 

 

 

[Angular Directive] Assign a Structual Directive a Dynamic Context in Angular 2

标签:nbsp   pass   ati   tor   struct   math   exp   custom   under   

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

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