简体   繁体   中英

Why checkbox event status returns string “on” instead of true/false?

I have a custom checkbox as child component which is being added in a parent component. I pass the ngModel , name etc. correctly and try to update the model with the status true/false based on checkbox status using EventEmitter .

Unfortunately the status I get is "on" as a string instead of boolean

Via Chrome console, I can track the status and the event . It works correct and puts out the expected result. Just the model and two way binding gets a string value and in my case it's "on" , and it keeps this string even if I uncheck the checkbox. in other words there is even no "off"

child.component.html:

<input type="checkbox"
        name="{{passCheckBoxName}}" 
        #ngForm="ngModel"
        [ngModel]="model" 
        (ngModelChange)="onChange($event)"
        required>

child.component.ts :

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

onChange(event) {
    console.log('this.model: ' + ${this.model});
    this.model = event;
    // event.checked doesn't work for me. output then is undefined
    // this.model = event.checked;
    console.log(event);
    this.modelChange.emit( event ); 
    // event.checked doesn't work for me. output then is undefined
    // this.modelChange.emit( event.checked ); 
}

parent.component.html :

<child-checkbox [parentFormGroup]="form"
                [name]="'nameOfCheckbox'"
                [ngModel]="name"" 
                ngDefaultControl>
</child-checkbox>

I have done some code for you: https://stackblitz.com/edit/angular-odkm2n?file=src%2Fapp%2Fhello.html the model value is boolean here 1. Why you create the child component only with checkbox? 2. Why you use Input() with "model" when you event don't take it into the child component? (also for the Output())

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