typescript Angular 2 RC4中的动态分量加载
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript Angular 2 RC4中的动态分量加载相关的知识,希望对你有一定的参考价值。
import { Component } from '@angular/core';
@Component( {
selector: 'something',
template: '<p>Testing: {{data}}</p>'
} )
export class SomethingComponent {
public data: string = 'Hello world!';
constructor() {}
}
import { Directive, Component, Input, ViewContainerRef, ComponentResolver, ComponentMetadata, ReflectiveInjector, ComponentFactory } from '@angular/core';
import { SomethingComponent } from './something-component';
@Directive( {
selector: 'dynamic-html-wrap'
} )
export class DynamicHTMLDirective {
@Input() src: string;
constructor( private vcRef: ViewContainerRef, private resolver: ComponentResolver ) {}
createComponentFactory( resolver: ComponentResolver, metadata: ComponentMetadata ) {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component( metadata )( cmpClass );
return resolver.resolveComponent( decoratedCmp );
}
ngOnChanges() {
if (!this.src) return;
const metadata = new ComponentMetadata( {
selector: 'dynamic-html',
directives: [ SomethingComponent ],
template: this.src,
} );
this.createComponentFactory( this.resolver, metadata )
.then( factory => {
const injector = ReflectiveInjector.fromResolvedProviders( [], this.vcRef.parentInjector );
this.vcRef.createComponent( factory, 0, injector, [] );
} );
}
}
import { Component } from '@angular/core';
import { DynamicHTMLDirective } from './dynamic-html.directive';
@Component( {
selector: 'main-layer',
directives: [ DynamicHTMLDirective ],
template: '<dynamic-html-wrap [src]="data"></dynamic-html-wrap>'
} )
export class AppComponent {
public data: string = '<something></something>';
constructor() {}
}
以上是关于typescript Angular 2 RC4中的动态分量加载的主要内容,如果未能解决你的问题,请参考以下文章
如何将 Angular 2 RC 1(或更早版本)表单迁移到 Angular 2 RC 2 / RC 4 新表单
Angular 2+:如何在 Angular 的 Typescript 组件中解析 json 数据
如何使用 TypeScript 在我的 Angular 2 组件中声明模型类?
Angular 2\TypeScript 中 export 关键字的确切含义是啥?
如何在 Angular 2 / Typescript 中声明全局变量? [关闭]
在 Angular 2 / Typescript 中使用 IScroll