Reputation: 10685
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?
Upvotes: 1
Views: 900
Reputation: 55443
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);
}
}
Upvotes: 0
Reputation: 10685
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);
}
}
Upvotes: 1