Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Component in Angular with ngModel and multiple fields

So lets say I want a create a custom component in Angular 2+ for the following class

public class user {
    name: string;
    id: number;
    address: string;
}

I've created a custom component

<input [(ngModel)]="name" />
<input [(ngModel)]="id" />
<input [(ngModel)]="address" />

I've added this custom component into my main page

<user-component></user-component>

What I want to do now is pass the User class as ngModel inside my custom component and bind it with public user:User variable in my main page class. Something like this

<user-component [(ngModel)]="user"></user-component>

I've found few examples of using ControlValueAccessor, NG_VALUE_ACCESSOR but all these examples work with single component like one text input. Is there a way to make it work for multiple inputs inside the custom component as well?

like image 966
casper123 Avatar asked Sep 14 '26 09:09

casper123


1 Answers

The way to achieve this is to use @Input on the UserComponent

export class UserComponent {
  @Input() user: User;
}

Then binding to the input you declared in your parent template

<user-component [user]="user"></user-component>

Now this is only one way, input to the UserComponent,

To make it two ways like ngModel works you would need to add the output EventEmiter As follows

export class UserComponent {
  @Input() user: User;
  @Output('userChange') emitter: EventEmitter<User> = new EventEmitter<User>();
}

Note that the userChange keyword is important here to make it work.

Only then you would be able to write the two way binding

<user-component [(user)]="user"></user-component>

Adding a bit of reading docs here angular.io/guide/template-syntax#property-binding-property

Also with just a google search away, i was able to find this also good SO answer on the same topic custom-input-and-output-on-same-name-in-angular2-2-way-binding

like image 121
Simplicity's_Strength Avatar answered Sep 15 '26 21:09

Simplicity's_Strength



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!