我通过组件工厂将组件动态添加到页面中。如何将每个click事件绑定到一个函数(将id作为每个参数传递)?这是我的代码:
component / card-one / card-one.html:
>>> binary = "0100100001000101010011000100110001001111001000000101011101001111010100100100110001000100"
>>> ''.join([chr(int(binary[i:i+8], 2)) for i in range(0, len(binary), 8)])
'HELLO WORLD'
component / card-one / card-one.ts :
<ion-card>
<ion-card-header>
{{ title }}
</ion-card-header>
<ion-card-content>
{{ data }}
</ion-card-content>
</ion-card>
并在 page / home / home.ts 中:
import { Component, Input } from '@angular/core';
import { ProcessComponent } from '../process';
@Component({
selector: 'card-one',
templateUrl: 'card-one.html'
})
export class CardOneComponent implements ProcessComponent {
@Input() data: any;
@Input() title: any;
constructor() {}
}
谢谢!
答案 0 :(得分:1)
您可以在每个组件中定义一个@HostListener
,这将解决单击该组件本身的问题
示例
export class CounterComponent {
public counter:number = 0
@HostListener('click') onClick() {
this.counter++;
}
}
@HostListener('click') onClick() {
this.counter++;
}
已更新
我仍然不确定您所说的添加点击事件以创建组件的内容,但这也许可以帮助您创建output
属性并订阅该属性,并且每次用户点击组件
请参阅此演示,在该示例中,我将像您一样创建动态组件,并传递数据并处理该组件上的click事件
计数器组件
export class CounterComponent {
@Input() counter:number = 0;
@Output() onClick=new EventEmitter();
@HostListener('click') emitClick() {
this.counter++;
this.onClick.emit(`this user click ${this.counter}`);
}
}
应用组件
@Component({
selector: 'my-app',
template: `
<template #counters></template>
`,
})
export class App {
@ViewChild("counters", { read: ViewContainerRef }) container;
componentRef: ComponentRef<any>;
constructor(private resolver: ComponentFactoryResolver) { }
ngOnInit() {
this.container.clear();
const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(CounterComponent);
this.componentRef = this.container.createComponent(factory);
this.componentRef.instance.counter = 10;
this.componentRef.instance.onClick.subscribe(data => this.handler(data));
}
handler(countData) {
console.log(`handler : data => ${countData}`)
}
ngOnDestroy() {
this.componentRef.destroy();
}
}