您的位置:首页 > Web前端 > AngularJS

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

2017-01-16 19:18 489 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐