2

I'm trying to bind the value of a map to html checkbox in angular2.

    this.profilType = new Map<string, boolean>();
    this.profilType.set("public", true);

to

    <input type="checkbox" [(ngModel)]="profilType['public']"/>

I tried this before, but it caused errors.

    <input type="checkbox" [(ngModel)]="profilType.get('public')"/>

Currently, no errors are displayed but it seems that there's no binding neither.

I found some solutions by using (click) mechanism but this are not relevant. Checkbox really need to react to component change.

Is there a way to do that or should I use different approach (advices are welcome too).

Thanks

0

1 Answer 1

4

I could only get the "banana in a box" syntax to work with getters/setters:

  get isPublic(): boolean {
    return this.profilType.get("public");
  }

  set isPublic(val: boolean) {
    this.profilType.set("public", val);
  }

  <input type="checkbox" [(ngModel)]="isPublic" />

But you can call the map directly like this:

<input type="checkbox" [ngModel]="profilType.get('public')" (ngModelChange)="profilType.set('public', $event)" />

Note that those getters will be called very often. If performance is an issue, you might be better off copying the boolean to/from the map using ngModelChange:

  this.isPublic = true;
  this.profilType.set("public", true);

  public setPublic() {
    this.profilType.set("public", this.isPublic);
  }

<input type="checkbox" [(ngModel)]="isPublic" (ngModelChange)="setPublic()" />
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, it seems to work fine for now. Of course, there is a lot of code to write more (getter/setter for each entry of map). It will allow to reduce a lot the html code by the way. Thanks Franck Modica. My rep is too low to rate you, sorry. I don't know if performance will be a issue here. I have very few feedback on this.
I updated my example to show you can call the map directly: <input type="checkbox" [ngModel]="profilType.get('public')" (ngModelChange)="profilType.set('public', $event)" />. Less getters/setters, but more HTML.
It works perfectly. I tried a similar solution at first, but I let parenthesis [(ngModel)] instead of [ngModel]. It caused a lot of error hard to read for a beginner as I am. Thanks again.
@chd, since this answer solved your issue, kindly accept the answer by clicking the grey tick under the voting of the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.