1

I am using Angular 4 and Typescript, I have a table of <select>s in my template:

<tr *ngFor="let task of tasksDetails">
    <td>{{task.name}}</td>
    <td>
        <select class="form-control" [(ngModel)]="task.uiMetadata.worker">
            <option value="">Select worker</option>
            <option *ngFor="let worker of workers" [value]="worker.resource.id">{{worker.resource.name}}</option>
        </select>
    </td>
</tr>

Within another component I am able to add/remove to the workers list and it is output to a Subject which this component subscribes to:

this.workerRemoved.subscribe(worker => {
    _each(this.tasksDetails, taskTemplate => {
        if (taskTemplate.uiMetadata.worker === member.resourceId) {
            taskTemplate.uiMetadata.worker = '';
        }
    });
});

The problem is that while the subscription updates the field in the variable, ngModel is not picking up the change and reflecting it in the UI.

Chrome DevTools output

So we end up with the situation where ng-reflect-model is showing "11", the worker variable is an empty string, and the select shows as blank because the "11" option has been removed.

How do I get Angular to keep the model in sync with the change I made in the subscription? I have tried wrapping it in an NgZone.run() and also calling ChangeDetectorRef.detectChanges() but neither would update the ng-reflect-model value.

Here is a Plunker reproducing the error

4
  • Can you create a plunker to reproduce the issue? Commented May 26, 2017 at 5:26
  • @echonax added link to Plunker Commented May 28, 2017 at 21:38
  • 1
    plnkr.co/edit/SGbhsySRZAxWgWuANCwC?p=preview Commented May 29, 2017 at 4:29
  • 1
    @yurzui you should provide it as an answer so that OP can accept it :-) Commented May 29, 2017 at 4:34

1 Answer 1

2

I found the solution thanks to yurzui pointing me in the right direction:

if (taskTemplate.uiMetadata.worker === member.resourceId) {

changes to

if (+taskTemplate.uiMetadata.worker === +member.resourceId) {

So that the strict equality is comparing numbers. The form input was converting the value into a string. Sometimes the easy ones can get ya.

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.