简体   繁体   中英

Angular2 ngModel checkbox undefined

Just a quick question if anyone knows how to solve this but I have some issues with a checkbox input.

It's configured in the following way

<input type="checkbox" [(ngModel)]="settings.ht_enabled" (ngModelChange)="changeSetting('ht_enabled')" id="setting-ht_enabled"> <label for="setting-ht_enabled">ht enabled</label>

Every time I click the checkbox the value of my model becomes undefined, and the (ngModelChange) gets triggered which only does a console.log . The settings get properly set and I see the checkbox that is checked. Only when I actually click it the value of my model becomes undefined.

Another thing to note is that this Angular2 project is running as a web worker.

Did anyone had any similar issues and knows how to solve this?

The component behind this piece of HTML is

@Component({
  selector: 'app-setting-form',
  templateUrl: './setting-form.component.html',
  styleUrls: ['./setting-form.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SettingFormComponent {
  settings: Setting;

  constructor(
    private service: SettingService,
    private cdr: ChangeDetectorRef,
    private messageBrokerService: MessageBrokerService,
  ) {
    this.messageBrokerService.send('access_token', '', this.initialize.bind(this));
  }

  initialize(token) {
    this.service.getSettings(token).subscribe(settings => this.handleSettings(settings));
  }

  handleSettings(settings: any) {
    this.settings = new Setting(settings);
    this.cdr.markForCheck();
  }

  changeSetting(setting: string) {
    console.log(this.settings);
  }
}

I've made a quick workaround as it seems that the value of a checkbox doesn't set a ngModel properly in Angular2. I don't know if this is something that has to do with the project running within a web worker but I got it working as follows.

<input type="checkbox" [(ngModel)]="settings.ht_enabled" (click)="changeSetting('ht_enabled')" id="setting-ht_enabled"> <label for="setting-ht_enabled">ht enabled</label>

and the changeSettings function is

changeSetting(setting: string) {
  this.settings[setting] = !this.settings[setting];
  console.log(this.settings);
}

I removed the (ngModelChange) and added my own click event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM