Get Value From Select Option in Angular 4

前端 未结 5 1130
难免孤独
难免孤独 2020-11-28 10:09

How do I get the value from the select option in Angular 4?

I want to assign it to a new variable in the component.ts file. I\'ve tried this but outputs nothing.

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 11:09

    This is very simple actually.

    Please notice that I'm

    I. adding name="selectedCorp" to your select opening tag, and

    II. changing your [value]="corporationObj" to [value]="corporation", which is consistent with the corporation in your *ngFor="let corporation of corporations" statement:

     

    And then in your .ts file, you just do the following:

    HelloCorp(form: NgForm) {
       const corporationObj = form.value.selectedCorp;
    }
    

    and the const corporationObj now is the selected corporation object, which will include all the properties of the corporation class you have defined.

    NOTE:

    In the html code, by the statement [value]="corporation", the corporation (from *ngFor="let corporation of corporations") is bound to [value], and the name property will get the value.

    Since the name is "selectedCorp", you can get the actual value by getting "form.value.selectedCorp" in your .ts file.

    By the way, actually you don't need the "#corporation" in your "select" opening tag.

提交回复
热议问题