加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

从Angular 4中的选择选项中获取价值

发布时间:2020-12-17 07:17:58 所属栏目:安全 来源:网络整理
导读:如何从Angular 4中的select选项中获取值? 我想将它分配给component.ts文件中的新变量.我试过这个,但没有输出任何东西. 你也可以用[(ngModel)]来做吗? component.html form class="form-inline" (ngSubmit)="HelloCorp(f)" #f="ngForm" div class="select"
如何从Angular 4中的select选项中获取值?

我想将它分配给component.ts文件中的新变量.我试过这个,但没有输出任何东西.

你也可以用[(ngModel)]来做吗?

component.html

<form class="form-inline" (ngSubmit)="HelloCorp(f)" #f="ngForm">
     <div class="select">
         <select class="form-control col-lg-8" #corporation required>
             <option *ngFor="let corporation of corporations" [value]="corporationObj">{{corporation.corp_name}}</option>    
         </select>
             <button type="submit" class="btn btn-primary manage">Submit</button>
     </div>
</form>

component.ts

HelloCorp() {
const corporationObj = corporation.value;
}
作为将军(参见Stackblitz: https://stackblitz.com/edit/angular-gh2rjx):

HTML

<select [(ngModel)]="selectedOption" name="first">
   <option *ngFor="let o of options">
      {{o.name}}
   </option>
</select>
<button (click)="print()">Click me</button>

<p>Selected option: {{ selectedOption }}</p>
<p>Button output: {{ printedOption }}</p>

Typescript

export class AppComponent {
  selectedOption: string;
  printedOption: string;

  options = [
    { name: "option1",value: 1 },{ name: "option2",value: 2 }
  ]
  print() {
    this.printedOption = this.selectedOption;
  }
}

在您的特定情况下,您可以像这样使用ngModel:

<form class="form-inline" (ngSubmit)="HelloCorp()">
     <div class="select">
         <select [(ngModel)]="corporationObj" class="form-control col-lg-8" #corporation required>
             <option *ngFor="let corporation of corporations"></option>    
         </select>
         <button type="submit" class="btn btn-primary manage">Submit</button>
     </div>
</form>

HelloCorp() {
  console.log("My input: ",corporationObj);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读