我创建了多个带有一些输入字段的动态组件。现在,我想在单击Submit按钮时将所有输入值发送到其他组件。
场景是,
- 连续5次点击添加按钮。现在,它将创建5行输入字段 然后,点击提交按钮,它将提醒所有输入值。在这里,我试图使用@Input/@Output的问题,但我不能让它运行。
砰砰作响
import { Component, ViewContainerRef, ElementRef, ComponentRef, ComponentResolver, ViewChild } from '@angular/core';
@Component({
template: `
<div id=item{{_idx}} style="border: 1px solid red">Test Component
<input type="text"/>
<button (click)="remove()">Remove</button>
<button (click)="add1()">Add</button>
</div>`
})
class DynamicCmp {
_ref: ComponentRef;
_idx: number;
constructor(private resolver: ComponentResolver, private location:ViewContainerRef) { }
remove() {
this._ref.destroy();
}
add1() {
this.resolver.resolveComponent(DynamicCmp).then((factory:ComponentFactory<any>) => {
let ref = this.location.createComponent(factory, 0);
// this._dcl.loadNextToLocation(DynamicCmp, this._e).then((ref) => {
ref.instance._ref = ref;
ref.instance._idx = this._idx++;
});
}
}
@Component({
selector: 'my-app',
template: `
<button (click) = "add()" > Add new component </button >
<button (click) = "submit()" > Submit </button >
<button (click) = "removeall()" > Remove All </button >
<div class="ttt11" id="ttt" #location ></div>
`
})
export class AddRemoveDynamic {
idx: number = 0;
@ViewChild('location', {read: ViewContainerRef}) location:ViewContainerRef;
constructor(private resolver: ComponentResolver) { }
add() {
this.resolver.resolveComponent(DynamicCmp).then((factory:ComponentFactory<any>) => {
let ref = this.location.createComponent(factory)
// this._dcl.loadIntoLocation(DynamicCmp, this._e, 'location').then((ref) => {
ref.instance._ref = ref;
ref.instance._idx = this.idx++;
});
}
submit(){
}
}
你能帮我一下吗?
非常感谢您的支持。您需要跟踪您在父组件中创建的动态组件。
export class AddRemoveDynamic {
private components = [];
然后当你创建一个新组件时,把它的组件ref推入组件数组
add() {
this.resolver.resolveComponent(DynamicCmp).then((factory:ComponentFactory<any>) => {
let ref = this.location.createComponent(factory)
// this._dcl.loadIntoLocation(DynamicCmp, this._e, 'location').then((ref) => {
ref.instance._ref = ref;
ref.instance._idx = this.idx++;
this.components.push(ref);
});
}
最后,提交时只需遍历组件数组并提取它的输入值。
submit(a: any){
let componentThings = this.components.map((compRef) => compRef.instance.thing);
alert(componentThings);
}
工作恰好