mardi 3 juillet 2018

Custom Checkbox: Why ngModule can't get/update the boolean checkbox status?

I use a custom checkbox component. I add it in the parent component. I assign the ngModule and I can access its status.

The issue is that I can't manage to get its boolean status true/false. It always throws true. The console log gives always the correct status depending in checked or not.

But the ngModule somehow doesn't update the correct status.

checkbox.component.html:

<mat-checkbox 
            value="true" 
            name="" 
            [(ngModel)]="model" 
            (ngModelChange)="onChangeCheck($event)"
            required="">     
</mat-checkbox>

checkbox.component.ts:

export class CheckboxComponent implements OnInit {  
    public parentFormGroup: FormGroup;

    @Input('label') inputLabel: string;
    @Input('name') checkBoxName: string;
    @Input() required: boolean;

    @Input() model: boolean;
    @Output() modelChange: EventEmitter<any> = new EventEmitter();

    onChangeCheck(event) {
        this.model = event.checked;
        console.log(`this.model => ${this.model}`);
        this.modelChange.emit(this.model);
    }

    constructor( 
    ) { }

    ngOnInit() {
    }
}

And here I do have the component where I embed the custom checkbox. user-profile.component.html:

<app-checkbox 
           [parentFormGroup]="form"
           [name]="'tc'"
           [ngModel]="name"
           [required]="true" 
           ngDefaultControl>
</app-checkbox>

When I load the page first time and use , I see:

{
  "tc": ""
}

When I check the checkbox, it become:

{
  "tc": "true"
}

which is not correct. it can't be string. it should be boolean true.

In the other hand the browser console for console.log('this.model =>' + this.model); says: undefined.

Has it to do with Angular Material or a wrong implementation of ngModule?




Aucun commentaire:

Enregistrer un commentaire