I have a component using the primeng checkbox:
<div *ngFor="let user of users">
<p-checkbox
[name]="'0' + user.id"
[value]="'User:' + user.id"
[ngModel]="getUserModel()"
(ngModelChange)="change($event)">
</p-checkbox>
<p-checkbox
[name]="'0' + user.id"
[value]="'Admin:' + user.id"
[ngModel]="getUserModel()"
(ngModelChange)="change($event)">
</p-checkbox>
</div>
getUserModel() {
var model = [];
this.users.forEach(u => {
if(u.category === 'Admin')
model.push('Admin:' + u.id);
else
model.push('User:' + u.id);
};
return model;
}
When I do that the page breaks, it seems to call the getUserModel()
method in loop forever. How can I assign the model dynamically?
I don't know why your site breaks, but Angular accesses the values in ngModel quite often, so in general it's not a good idea to bind a function. Instead it's better to build up the values once and then bind ngModel to a variable. Angular tracks the changes of that variable, so if you change it, Angular does too.
In your case, you can add an additional field to your Users model where the result of getUserModel() is saved and then access it like this:
<div *ngFor="let user of users">
<p-checkbox
[name]="'0' + user.id"
[value]="'User:' + user.id"
[ngModel]="user.resOfGetUserModel"
(ngModelChange)="change($event)">
</p-checkbox>
// ... code omitted
</div>
In your ts you do a for loop over your users where you execute getUserModel() for each entry of Users and save it to "resOfGetUserModel".
If users is the result of getUserModel, then obviously you put that directly, like this: [ngModel]="users"