Freddy Bonda
Freddy Bonda

Reputation: 1259

Angular custom ngModel [(...)]

I have created a custom component and would like to create a custom [(ngModel)] for it. Say I have this in a component:

<input [(ngModel)]="var1"> // (first input)
<my-custom-input [injectedNgModel]="var1"><my-custom-input>

And in my <my-custom-input> I have this:

@Input() injectedNgModel: any;
...
<input [(ngModel)]="injectedNgModel"> // (second input)

Then, when you enter text in the (first input), it will update the (second input). But when you enter text in the (second input), it doesn't change the (first input) which is var1.

How can I make an @Input send data back to it's parent?

What I do not want is an @Output because then the component is too busy:

<my-custom-input [injectedNgModel]="var1" (outputNgModel)="var1">

I was hoping for something like [(injectedNgModel)]="x" but I can't get it to work like this.

https://stackblitz.com/edit/angular-upyf32

Upvotes: 0

Views: 1459

Answers (1)

Rahul
Rahul

Reputation: 2128

The word Change does the magic for you which creates the two way data binding - Means you have [ngModel] and (ngModelChange) events to bind as [(ngModel)] banana like syntax

So in your case you need to have injectedNgModel as @Input() and injectedNgModelChange as @Output() event emitter

Try something like this

 modelValue: string;

    @Output()
    injectedNgModelChange: EventEmitter<any> = new EventEmitter<any>();

    @Input()
    get injectedNgModel(): string {
        return this.modelValue;
    }

    set injectedNgModel(val: string) {
        this.modelValue= val;
        this.injectedNgModelChange.emit(this.modelValue);
    }

This creates the two way data binding to your input variable injectedNgModel and you will get the updated value on both parent and child components

You can access it <my-custom-input [(injectedNgModel)]="var1"> - That's the magic for the word Change

In your child component you can read the get and set property like this <input [(ngModel)]="injectedNgModel">

Hope this helps you - Happy coding :)

Upvotes: 1

Related Questions