首页 文章

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

提问于
浏览
0

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

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

关于如何实现这一点的任何想法,还是我可以采取的另一条路线?

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

实际的形式更复杂,所以我想避免使用特定的事件,比如观察每个输入的变化,以便在可能的情况下手动触发事件 Launcher .

父模板:

<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 回答

  • 2

    您可以使用 NgFormvalueChanges

    Component

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

    Template

    <form #myForm='ngForm' ...>
        // your select , input or nany form elements
    </form>
    

    以上代码用于模板驱动表单,

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


    不错的方法是:

    this.myForm.statusChanges.subscribe(res => {
        if (res === 'VALID') {
           // emit(this.myForm.values)
        }
    });
    

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

相关问题