首页 > 解决方案 > Angular 如何在动态组件中使用@decorators?

问题描述

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

// 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() 获取短信数据;// 错误,装饰器在这里无效

一些想法将是可观的。

谢谢。

标签: angularangular5

解决方案


推荐阅读