1

I am creating some kind of auto word correction module in Angular2.

I have an EventEmitter setup in my child component

import {Component, Input, Output, EventEmitter} from '@angular/core';
...
export class StudyThumbsComponent{
  @Output() notify: EventEmitter<any> = new EventEmitter();
  ...
  verify(input, i) {
    this.answer.input = input;
    this.answer.id = i;
    this.notify.emit(this.answer);
  }
}

"i" is the input's index as there are many inputs to check within the component.

The child component html:

<input type="text" [(ngModel)]="item.input" (keyup)="verify($event, i)">

The logic for auto word correction is in the parent component since there could be different types of child components requiring the auto word correction feature:

export class ParentComponent{
  verify(event:any, i) {

    var answer = event.target.value;

    // the variable answer gets corrected/modified and assigned to...
    var correctedAnswer;

  }

  onNotify(answer) {
    this.verify(answer.input, answer.id);
  }

}

This posted code works ups to that point, so the question is, how do I update the child's component input with the corrected answer (correctedAnswer) ?

Pat M
  • 5,966
  • 7
  • 24
  • 34

1 Answers1

1

Have an @Input string inside your children component that receives the output from each validation. That validated variable will be changed by the parent's verify function.

@Input() validated: String;

You can detect input changes by using ngOnChanges()

Alternatively:

Move all your logic about the spell checker into a service.

Then you can import that service on all your the components you need to use the spell checker in.

Also, I don't think a spell checker needs to know about the field nor the index. It should be good to go with the text input:

export class SpellCheckerService {

  validate(str): String {

  }

Depending on how you have everything structured, I think it'd even probably fit best into an /utils folder.

zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • Thanks zurfyx. Both seem to work well. Went with first option since it matched better the other parts of my code. – Pat M Jan 03 '17 at 22:18