Issue
Since I use inputs with a lot of the same directives and .css classes applyed, I want to extract the repeated code to some component like this:
@Component({
selector: "app-input",
template: `
<div class="...">
<input type="..." name="..." class="..." [(ngModel)]="value" someDirectives...>
<label for="...">...</label>
</div>
`,
...
})
export class InputComponent implements OnInit {
// some implementation connecting external ngModel with internal "value" one
}
The problem here is creating a component in such a way that it can be used with ngModel as an ordinary input:
<app-input [(ngModel)]="externalValue" ... ></app-input>
I've found several solutions on the internet that can be partially or completely outdated now like: Angular 2 custom form input Can this be done in a better way in angular 6?
Solution
this can also be done like this, when you create a two way binding [()] you can bind it to a function using the same name + 'change' (in our case inputModel and inputModelChange) this way the ngModel will update when you trigger inputModelChange.emit('updatedValue'). and you only need to declare it once inside your component.
app-input.component.ts
import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
@Component({
selector: 'app-input',
template: ` <input type="text" [(ngModel)]="inputModel" (ngModelChange)="inputModelChange.emit(inputModel)"/>`,
styleUrls: ['./app-input.component.scss']
})
export class AppInputComponent {
@Input() inputModel: string;
@Output() inputModelChange = new EventEmitter<string>();
}
app.component.html
<app-input [(inputModel)]="externalValue"></app-input>
Answered By - omer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.