1

I have a component with this code inside:

<div class="form-group">
    <label for="title">Title</label>
    <input type="text" [(ngModel)]="model.title" name="title" required/>
</div>

I am trying to migrate the whole thing into another component, input-component:

@Component({
    selector: 'input-component',
    template: `
        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" [(ngModel)]="value" name="title" required/>
        </div>
    `
})
export class InputComponent {
    @Input() value: string;
}

So the first example code will be replaced with:

<input-component [value]="model.title"></input-component>

When model.title is changed, the value inside the HTML element is changed, however when I change the contents of the element, model.title does not change.

How can I achieve two-way data binding with this setup?

2 Answers 2

1

I needed to create an EventEmitter to do this:

@Component({
    selector: 'input-component',
    template: `
        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" [ngModel]="value" (ngModelChange)="onInput($event)" name="title" required/>
        </div>
    `
})
export class InputComponent {
    @Input() value: string;
    @Output() valueChange = new EventEmitter();

    public onInput(event: string) {
        this.value = event;
        this.valueChange.emit(event);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@PankajParkar it will not work without EventEmitter.
@micronyks parden me, I thought the other way :) Thanks for letting me know
0

Still better way would be,

<input-component [(value)]="model.title"></input-component>

    <input type="text" [(ngModel)]="value" name="title" 
                       (keyup)="update(value)" required/>      ///<<<### keyup


    export class InputComponent {
        @Input() value: string;
        @Output  valueChange:EventEmitter=new EventEmitter();  ///<<<### added

       update(value){
           this.valueChange.emit(value);
       }
    }

2 Comments

Why is this better (relying on keyup rather than ngModelChange)?
Opps ! I didn't see your answer properly. Yours is better and having no problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.