首页 > 代码库 > [Angular Directive] Assign a Structual Directive a Dynamic Context in Angular 2
[Angular Directive] Assign a Structual Directive a Dynamic Context in Angular 2
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。