每当对象内容发生更改时,角度触发器EventEmitter

时间:2017-10-18 13:27:11

标签: javascript angular output components eventemitter

我正在使用子组件来构建一个由递归子数组和对象组成的复杂对象。我想要一种使用实时绑定在父组件中访问此对象的方法。

对象中的值根据用户输入(选择框,输入等)发生变化,所以我需要一种方法来发出@Output()EventEmitter,并且只要它的属性发生变化,就会传递整个对象。

关于如何实现这一目标的任何想法,还是我可以采取的其他途径?

请参阅下面的一些概念代码,其中输入具有绑定到复杂对象中的深度值的双向数据,并且我需要通过以某种方式检测更改来将此更改发送到父级。

实际表单更复杂,因此我想避免使用特定事件,例如在每个输入中观察更改以手动触发事件发射器。

父模板:

<child-component (emitter)="emitterHandler($event)"></child-component>

父组件:

emitterHandler(obj){ console.log(obj); }

子组件:

@Output() emitter: EventEmitter<any> = new EventEmitter();    
complexObj = {data: 'test', lines: [{data: 'asd', time: 123},{data: 'xcv', time: 233}]};

儿童模板:

<input [(ngModel)]="complexObj.lines[0].data"></input>

1 个答案:

答案 0 :(得分:2)

您可以使用die()的{​​{1}}:

<强>组件

valueChanges

<强>模板

NgForm

上面的代码是针对模板驱动的表单,

以下是关于数据驱动表单的文章: https://alligator.io/angular/reactive-forms-valuechanges/

好的方法是:

@ViewChild('myForm') myForm: NgForm;

// this will be called when any input inside the form changes
this.myForm.valueChanges.subscribe(val => {
    // emit the event
});

这将在数据有效时发出值,并且在上面的代码中,无论值是对还是错,它都会触发事件。