首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态组件单击事件绑定-角2

动态组件单击事件绑定-角2
EN

Stack Overflow用户
提问于 2017-08-24 08:35:09
回答 1查看 1.8K关注 0票数 1

有可能重复,但我的情况有点不同。

我想为我的动态组件执行单击事件。

这是我的结构:

代码语言:javascript
复制
     <razor>
          <mvc-partial>
            <dynamic-html> // buttonPress(){console.log("Function called in dynamicHtml)
                          // Output() to call function in razor.ts
            </dynamic-html>
          </mvc-partial>
      <razor>

RenderingViewDynamic.ts文件

代码语言:javascript
复制
import {
    Component,
    Directive,
    NgModule,
    Input,
    Output,
    EventEmitter,
    ViewContainerRef,
    Compiler,
    ComponentFactory,
    ModuleWithComponentFactories,
    ComponentRef,
    ReflectiveInjector, OnInit, OnDestroy, ViewChild
} from '@angular/core';

import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any> | undefined>{   
    console.log(compiler)
    console.log(metadata)
    class DynamicComponent {
        @Output() buttonType: EventEmitter<string> = new EventEmitter<string>()

        // button click operation
        buttonPress() {
            this.buttonType.emit();
        }
    };
    const decoratedCmp = Component(metadata)(DynamicComponent);

    @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
    class DynamicHtmlModule { }

    return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
        .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
            console.log(decoratedCmp)
            console.log(moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp))
            return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
        });
}

@Component({
    selector: 'mvc-partial',
    template: `<div #dynamicHtml></div>`
})
//@Directive({ selector: 'mvc-partial' })
export class RenderingViewDynamic implements OnInit {
    @ViewChild('dynamicHtml', { read: ViewContainerRef }) target: ViewContainerRef;
    html: string = '<p></p>';
    @Input() url: string;
    cmpRef: ComponentRef<any>;

    constructor(private vcRef: ViewContainerRef, private compiler: Compiler, private http: Http) { }

    ngOnInit() {
        this.http.get(this.url)
            .map(res => res.text())
            .subscribe(
            (html) => {
                this.html = html;
                if (!html) return;

                if (this.cmpRef) {
                    this.cmpRef.destroy();
                }

                const compMetadata = new Component({
                    selector: 'dynamic-html',
                    template: this.html,
                });

                createComponentFactory(this.compiler,compMetadata)
                    .then(factory => {
                        //const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
                        this.cmpRef = this.target.createComponent(factory!);
                    });
            },
            err => console.log(err),
            () => console.log('MvcPartial complete')
            );

    }

    ngOnDestroy() {
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
    }  

}

razor.component.html

<mvc-partial [url]="'/View/Index'" (buttonType)="click()"></mvc-partial>

razor.component.ts

click(){ console.log("In razor") }

我的问题是,按钮在我的dynamic中,希望将其事件绑定到razor.ts中。

就像<dynamic-html>-<mvc-partial>-<razor>,我怎么能做到呢?

更新:尝试与服务通信

代码语言:javascript
复制
class DynamicComponent {
        constructor(private appService: AppService) { }

        buttonPress() {
            this.appService.onButtonClickAction.emit()
        }
    };
    const decoratedCmp = Component(metadata)(DynamicComponent);

    @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp], providers: [AppService] })

错误pops:无法解析DynamicComponent:(?).的所有参数

通过添加@Inject(forwardRef(() => AppService)解决上述错误

代码语言:javascript
复制
constructor( @Inject(forwardRef(() =>  AppService)) private appService: AppService) { } 
EN

回答 1

Stack Overflow用户

发布于 2017-08-24 09:24:14

通过使用EventEmitter,您可以将单击事件从您的子事件冒泡到您的父级:

代码语言:javascript
复制
clickEmitter = new EventEmitter();

clickEmitter.emit();

<your-child-component (clickEmitter)="functionInParent()"></your-child-component>

编辑:如果您想按照注释:<dynamic-html>-<mvc-partial>-<razor>到达您的子组件,可以使用hashtag (#)和hashtag的名称或组件名称引用组件

代码语言:javascript
复制
@ViewChild(MvcPartialComponent) mvcPartialComponent: MvcPartialComponent;

<mvc-partial #mvc-partial></mvc-partial>
@ViewChild('mvc-partial') mvcPartialComponent: MvcPartialComponent;

等。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45856730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档