angularangularjs-ng-value

Angular "select" binding to a true/false value not working


I'm trying to bind my select element to a true/false value. The binding seems to happen as the -- select -- option isn't shown, meaning Angular knows there's a value, but the display is just blank by default. If I click on it then I see my Yes and No choices, but it's not being initially set.

        <select class="form-control" id="primary" name="primary" required
                [(ngModel)]="primaryValue">
            <option *ngIf="primaryValue === null" [ngValue]="null">-- Select --</option>
            <option [ngValue]="true">Yes</option>
            <option [ngValue]="false">No</option>
        </select>

The primaryValue is defined like this in the typescript file:

@Input() primaryValue: boolean;

If I do this with just an input it works fine, but if I use primaryValue as both input and output, then it doesn't work. You can see an example on StackBlitz


Solution

  • Finally tracked this down. In the component that showed the questions I had this as part of the @Component definition:

    viewProviders: [  // This makes the whole child participate in the parent's form validation
        {
            provide: ControlContainer,
            useExisting: NgForm
        }
    ]
    

    which I had seen on the web say that it makes the child controller's components be part of the parent component's form validation. As soon as I removed that part, everything started working properly.