Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 角度2模板可以';无法获取事件绑定_Typescript_Angular - Fatal编程技术网

Typescript 角度2模板可以';无法获取事件绑定

Typescript 角度2模板可以';无法获取事件绑定,typescript,angular,Typescript,Angular,我尝试创建自己的structure指令,它可以创建一些DOM结构(在我的例子中是按钮组)。我想为包装器和子类创建自定义标记,并应用自定义类 我停留在瞬间输出事件上。我完成了指令。它起作用了。(我在这个指令中进行DOM操作)。 但现在我不能从这个指令中发出事件。我发现答案是,这是因为事件应该是静态的。类似-(单击)=“some()” 但是如果我的孩子是动态创建的,我该怎么做呢?(目前我使用的是AddEventListener) 并且出现以下错误:事件绑定onBtnClick not embedde

我尝试创建自己的structure指令,它可以创建一些DOM结构(在我的例子中是按钮组)。我想为包装器和子类创建自定义标记,并应用自定义类

我停留在瞬间输出事件上。我完成了指令。它起作用了。(我在这个指令中进行DOM操作)。 但现在我不能从这个指令中发出事件。我发现答案是,这是因为事件应该是静态的。类似-
(单击)=“some()”
但是如果我的孩子是动态创建的,我该怎么做呢?(目前我使用的是
AddEventListener

并且出现以下错误:事件绑定onBtnClick not embedded template上的任何指令发出

谢谢你提供的任何信息

以下是我的组件代码:

import {Component, Injectable, Input, Output, EventEmitter, OnInit, ElementRef} from '@angular/core';

import { BtnGroupChildStructure } from './button_group.directive';
import { Config } from 'appConfig';
/* ------- !Config  ---------*/

const MODULE_NAME: string = 'button_group';
const MODULE_PATH: string = `${Config.getProdFolderName()}/shared/components/${MODULE_NAME}`;

@Component({
    selector : 'cgm_button_group',
    template : `<template *btnGroupChildStruct="config" 
                (onBtnClick)="t_handleBtnClick($event)"></template>`,
    host : {'class': 'button-group-box'},
    directives : [
        BtnGroupChildStructure
    ]
})
@Injectable()
export class ButtonGroupComponent implements OnInit {

    private _config: Object;

    @Input() config(val: Object) {
        console.log(val);
        Object.assign(this._config, val);
        console.log(this._config);
    }

    @Output onBtnClick = new EventEmitter<string>();

    ngOnInit() {

    }

    private t_handleBtnClick(buttonName: string): void {
        this.onBtnClick.emit(buttonName);
    }
}
从'@angular/core'导入{Component,Injectable,Input,Output,EventEmitter,OnInit,ElementRef};
从“./button_group.directive”导入{BtnGroupChildStructure};
从'appConfig'导入{Config};
/* ------- !配置---------*/
常量模块名称:字符串='按钮组';
const MODULE_PATH:string=`${Config.getProdFolderName()}/shared/components/${MODULE_NAME}`;
@组成部分({
选择器:“cgm_按钮组”,
模板:``,
主机:{'class':'button group box},
指令:[
BtnGroupChildStructure
]
})
@可注射()
导出类ButtonGroupComponent实现OnInit{
私有配置:对象;
@Input()配置(val:Object){
控制台日志(val);
Object.assign(this.\u config,val);
console.log(this.\u config);
}
@Output onBtnClick=new EventEmitter();
恩戈尼尼特(){
}
专用t_把手单击(按钮名称:字符串):无效{
this.onBtnClick.emit(buttonName);
}
}
这是指令代码

import { Directive, Input, 
    ViewContainerRef, ElementRef, TemplateRef, OnInit, Output, EventEmitter } from '@angular/core'

@Directive({ selector : '[btnGroupChildStruct]'})
export class BtnGroupChildStructure implements OnInit {

    private _hostEl;
    private _config: Object = {};

    @Input() set btnGroupChildStruct(val: Object) {
        console.log(val);
        Object.assign(this._config, val);
    }

    @Output() onBtnClick = new EventEmitter<string>();

    constructor(
        private _templateRef: TemplateRef<any>,
        private _viewContainer: ViewContainerRef,
        private _elementRef: ElementRef
    ) {
        this._hostEl = this._elementRef.nativeElement.parentElement;

    }

    ngOnInit() {
        //console.log(this._templateRef);
        this._generateChilds();
        this._hostEl.appendChild(this._generateGroup());
        //this._viewContainer.createEmbeddedView(this._templateRef);
    }

    /**
     * _generateChilds -> generate childs structure
     * @returns {DocumentFragment}
     * @private
     */
    private _generateChilds(): DocumentFragment {
        let fragment = document.createDocumentFragment();

        if (this._config.hasOwnProperty('buttonNamesList')) {
            this._config.buttonNamesList.forEach((buttonName) => {
                let item = document.createElement(this._config.tagChild);
                this._addClasses(item, this._config.childClasses);
                item.textContent = buttonName;
                this._addClickHandler(item);
                fragment.appendChild(item);
            })
        } else {
            throw new Error('Button group Directive. _generateChilds. Can"t get _config buttonNamesList prop');
        }

        return fragment;

    }

    /**
     * _generateGroup -> generate button group
     * @returns {HTMLElement}
     * @private
     */
    private _generateGroup(): HTMLElement {
        let wrapperTag;
        if (this._config.hasOwnProperty('tagWrapper')) {
            wrapperTag = document.createElement(this._config.tagWrapper);
            this._addClasses(wrapperTag, this._config.wrapperClasses);
            wrapperTag.appendChild(this._generateChilds());
        } else {
            throw new Error('Button group Directive. _generateGroup. Can"t get _config tagWrapper prop');
        }

        return wrapperTag;
    }

    /**
     * _addClasses -> Add classes to el
     * @param el (HTMLElement) -> handled Element
     * @param classesStr (String) -> string of classes
     * @private
     */
    private _addClasses(el: HTMLElement, classesStr: string): void {
        if (!el || !classesStr) throw new Error('_addClasses. Missed one of parameter');
        el.className = classesStr
    }

    private _addClickHandler(el: HTMLElement): void {
        if (!el) throw new Error('_addClickHandler. Non exist element');
        el.addEventListener('click', (el) => {
            this.onBtnClick.emit(el.textContent);
        })
    }

}
import{指令,输入,
ViewContainerRef、ElementRef、TemplateRef、OnInit、Output、EventEmitter}来自“@angular/core”
@指令({选择器:'[btnGroupChildStruct]'})
导出类BtnGroupChildStructure实现OnInit{
私人宿舍;;
私有_config:Object={};
@Input()设置btnGroupChildStruct(val:Object){
控制台日志(val);
Object.assign(this.\u config,val);
}
@Output()onBtnClick=neweventemitter();
建造师(
private_templateRef:templateRef,
private _viewContainer:ViewContainerRef,
私人_elementRef:elementRef
) {
this._hotel=this._elementRef.nativeElement.parentElement;
}
恩戈尼尼特(){
//console.log(this.\u templateRef);
这个。_generateChilds();
这个。_hotel.appendChild(这个。_generateGroup());
//this.\u viewContainer.createEmbeddedView(this.\u templateRef);
}
/**
*_generateChilds->generateChilds结构
*@returns{DocumentFragment}
*@私人
*/
private _generateChilds():DocumentFragment{
让fragment=document.createDocumentFragment();
if(this.\u config.hasOwnProperty('buttonNameList')){
此._config.buttonNamesList.forEach((buttonName)=>{
让item=document.createElement(this.\u config.tagChild);
this.\u addClasses(项,this.\u config.childClasses);
item.textContent=按钮名称;
此.\u添加ClickHandler(项目);
片段。追加子项(项目);
})
}否则{
抛出新错误('Button group Directive.\u generateChilds.Can't get\u config ButtonNameList prop');
}
返回片段;
}
/**
*_generateGroup->生成按钮组
*@returns{HTMLElement}
*@私人
*/
private _generateGroup():HTMLElement{
让包装标签;
if(this._config.hasOwnProperty('tagWrapper')){
wrapperTag=document.createElement(this.\u config.tagWrapper);
this.\u addClasses(wrapperTag,this.\u config.wrapperClasses);
appendChild(this._generateChilds());
}否则{
抛出新错误('Button group Directive.\u generateGroup.Can“get\u config tagWrapper prop');
}
返回包装标签;
}
/**
*\u addClasses->将类添加到el
*@param el(HTMLElement)->已处理元素
*@param classesStr(String)->类的字符串
*@私人
*/
private _addClasses(el:HTMLElement,classesStr:string):void{
如果(!el | |!classesStr)抛出新错误(“u addClasses.Missed of parameter”);
el.className=classesStr
}
private\u addClickHandler(el:HTMLElement):void{
如果(!el)抛出新错误(“U addClickHandler.Non exist元素”);
el.addEventListener('单击',(el)=>{
this.onBtnClick.emit(el.textContent);
})
}
}

@Output
需要是
@Output()
Hi Gunter。对的我修复了它,但得到了相同的错误。如果在
标记上使用结构指令,请不要添加
*
前缀。这仅用于隐式使用
标记。我不知道如何从结构指令中侦听事件,但请在不使用
*
的情况下尝试,如果它有任何更改,请报告。如果结构指令在没有事件的情况下执行任何操作,可以尝试一下。如果删除
*
,则需要使用
[btnGroupChildStruct]=“…”
,否则将分配字符串
“config”
,而不是
@Input()config
的值。再次向Gunter致敬。当我尝试使用一些“real”标记(例如section)来代替模板标记时,tt不起作用,因为动态创建的元素没有在这个标记中呈现。这就是为什么我使用模板。因为我不知道如何将动态创建的元素放置在此标记中。我尝试使用this//this.\u viewContainer.createEmbeddedView(this.\u templateRef);但是我不知道如何创建对我的动态元素的引用。Plunker
@Output
的一个例子应该是
@Output()
Hi Gunter。