如何正确更改父级的子组件?

时间:2016-07-20 06:33:34

标签: typescript angular event-handling

我有以下构造的嵌套组件:

app.parent.component > app.container.component > app.containeritem.component 

例如:

app.parent.component

import ...
@Component({
    selector:'parent',
    template: '<container></container>,
    ....
})

app.container.component

import ...
@Component({
    selector: 'container',
    template: '<containeritem></containeritem>',
    ...
})

app.containeritem.component

import ...
  @Component({
        selector: 'containeritem',
        template: `<ul><li draggable="true"(dragend)="update.emit($event)">lorem</li></ul>`
        ...
    })

app.child.component内部发送拖动操作。那么,我如何在 app.parent.component 中正确获取 app.containeritem.component 的操作数据?

1 个答案:

答案 0 :(得分:2)

您只需使用OutputEventEmitter s:

传递活动

<强> app.parent.component

import ...
@Component({
    selector:'parent',
    template: '<container (onDrag)="doSomething($event)"></container>,
    ....
})
export class ParentComponent {
    doSomething(event) {
        console.log(event);
    }
}

<强> app.container.component

import ...
@Component({
    selector: 'container',
    template: '<containeritem (onDrag)="onDrag.emit($event)"></containeritem>',
    ...
})
export class ContainerComponent {
    @Output onDrag: EventEmitter = new EventEmitter();
}

<强> app.containeritem.component

import ...
@Component({
    selector: 'containeritem',
    template: `<ul><li draggable="true"(dragend)="onDrag.emit($event)">lorem</li></ul>`
    ...
})
export class ContainerItemComponent {
    @Output onDrag: EventEmitter = new EventEmitter();
}