Angular如何在动态组件中使用@decorators?

时间:2018-07-07 08:00:02

标签: angular angular5

基本上,我需要基于动态模板创建组件,并将父数据共享给新创建的组件,还需要将数据共享给其他组件。

// import
    @Component({
        selector: 'app-modal',
        template: `<div #vcf></div>`,
        providers: [AppsService],
        encapsulation: ViewEncapsulation.None,
    })
    export class AppModalComponent implements OnInit, OnDestroy, AfterViewInit {
    @ViewChild('vcf', {read: ViewContainerRef}) vcf: ViewContainerRef;

    private cmpRef: ComponentRef<any>;

    constructor(
        private appService: AppsService,
        private compiler: Compiler,
        private injector: Injector,
        private m: NgModuleRef<any>
    ) {}

    ngOnInit() { }

    ngAfterViewInit() {
        let template;
        const styles = [`input { width: 100px }`];
        this.appService.getAppTemplate().subscribe((templateData) => {
            console.log('dynamic html data ::: ', templateData); // ok
            template = templateData;
            // Component dynamically.
            const templateComponent = Component({template})(class DynamicTemplateComponent {

                @Input() sendSMS; // Error, Saying Decorators are not valid here

                someMethod() {
                    alert('some data submitting'); // working
                }
                addSMSData() {
                       alert('ok');
                }      
            });
            const templateModule = NgModule({
                imports: [RouterModule,  FormsModule, CommonModule],
                declarations: [templateComponent]
            })(class {});

            this.compiler.compileModuleAndAllComponentsAsync(templateModule)
                .then((factories) => {
                    const f = factories.componentFactories[0];
                    this.cmpRef = f.create(this.injector, [], null, this.m);
                    this.cmpRef.instance.name = 'templateFrm';
                    this.vcf.insert(this.cmpRef.hostView);
                });
        });
    }
}

这是我的虚拟模板,它也正在渲染和工作。

<input type="text" id="sms_title" [(ngModel)] ="sms_title" name="sms_title" placeholder="SMS title" required> <button type="submit" (click)="addSMSData()">Submit</button>

因此,如何在新创建的组件中使用装饰器,该组件具有即时的所有功能。

  

@Input()getSMSData; //错误,装饰器在这里无效

有些想法会很有意义。

谢谢。

0 个答案:

没有答案