Deniss M.
Deniss M.

Reputation: 4070

Angular (4): get a value for md-select through a function?

I have the following <md-select> element:

<md-select placeholder="{{'COMPANY.TYPE' | translate}}"
       required
       id="firmType"
       ngModel name="type"
       #type="ngModel"
       [(ngModel)]="checkType(company)"
       floatPlaceholder="never"
       class="full-width">
       <md-option *ngFor="let type of companyType" [value]="type.id">{{ type.name }}</md-option>
</md-select>

I want to be able to set the value of the select input via a function. This is obviously wrong, but I can't figure out a way to correct this.

This is the error I'm getting:

Error: Uncaught (in promise): InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': '[(ngModel)]value' is not a valid attribute name.
Error: Failed to execute 'setAttribute' on 'Element': '[(ngModel)]value' is not a valid attribute name.

updated (checkType function):

public checkType(company: Company): number {

        if (company['regNr'].includes('F', 0)) {
          console.log('found F');
          return 2;
        }
        console.log('found L');
        return 1;
      }

Upvotes: 0

Views: 153

Answers (1)

federico scamuzzi
federico scamuzzi

Reputation: 3778

try this:

 [ngModel]="selectedCompany"
           (ngModelChange)="onChange($event)"



<md-select placeholder="{{'COMPANY.TYPE' | translate}}"
       required
       id="firmType"
       ngModel name="type"
       #type="ngModel"
       [ngModel]="selectedCompany"
       (ngModelChange)="onChange($event)"

       floatPlaceholder="never"
       class="full-width">
       <md-option *ngFor="let type of companyType" [value]="type.id">{{ type.name }}</md-option>
</md-select>

Cause:

[ngModel]="selectedCompany" // show value (one way binding) (ngModelChange)="onChange($event)" // call your func 'on change'

then in you .ts file:

public checkType(ev : any): number { // here ev is the value of what you select (so a string)


        console.log(ev);
        return 1;
      }

Upvotes: 1

Related Questions