2

I have a Template Driven Form in which i am putting a checkbox that can toggle its value.

Component

public toggles = [
    { value: 'toggled', display: 'Toggled' },
    { value: 'untoggled', display: 'UnToggled' },
];

<div>
    <input type="hidden" name="toggle" [(ngModel)]="user.toggle">
    <div>
        <label>
            <input type="checkbox"
                [checked]="user.toggle === toggles[0].value" 
                (change)="$event.target.checked? (user.toggle =  toggles[0].value) : (user.toggle = toggles[1].value)">
            {{ toggles[0].display }}
        </label>
    </div>
</div>

The following works great, but when i am switching to Angular Material it just fails to works .

The material Template code

<input type="hidden" name="toggle" [(ngModel)]="user.toggle">
<md-checkbox [checked]="user.toggle === toggles[0].value"
               (change)="$event.target.checked?(user.toggle = toggles[0].value): (user.toggle = toggles[1].value)">
    {{toggles[0].display}}</md-checkbox>

I am getting the following Error in console, it says cannot read the property of undefined console,

TypeError: Cannot read property 'checked' of undefined
        at Object.eval [as handleEvent] (TemplateDrivenComponent.html:64)

I know the point where the error is occurring $event.target.checked angular cannot read this checked event on md-checkbox , how to get around this any pointers will be great

thanks

8
  • well, what is the value of $event.target ? Commented Apr 2, 2017 at 6:36
  • the value of $event.target is coming from the checkbox property as in the code without material it checks if the checkbox is checked or not Commented Apr 2, 2017 at 6:37
  • I know WHAT it is... but what is its VALUE Commented Apr 2, 2017 at 6:39
  • log the object you're trying to view the properties of, and it will probably shed light on what is going wrong Commented Apr 2, 2017 at 6:40
  • also why not just use this? Commented Apr 2, 2017 at 6:41

1 Answer 1

4

Looking at comments try the following hope this solves the issue i guess you need not use target with event in Material.

 <input type="hidden" name="toggle" [(ngModel)]="user.toggle">
        <md-checkbox [checked]="user.toggle === toggles[0].value"
                       (change)="$event.checked?(user.toggle = toggles[0].value): (user.toggle = toggles[1].value)">
            {{toggles[0].display}}</md-checkbox>
Sign up to request clarification or add additional context in comments.

Comments

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.