读取单选按钮值——Angular 2

Reading radio button value - Angular 2

本文关键字:Angular 单选按钮 读取      更新时间:2023-09-26

我正在尝试读取单选按钮值-在angular 2中,

index . html

<input type="radio" id="options1" name="function" value="create">
<input type="radio" id="options2" name="function" value="continue">

index.ts

@Component({
    selector: 'function',
    templateUrl: './client/components/function/index.html',
    styleUrls: ['./client/components/function/index.css'],
    providers: [],
    directives: [ROUTER_DIRECTIVES]
})

我需要根据单选按钮值是创建还是继续在html中显示一个div。

我试过了:

  1. 在typescript文件中使用document.getElementById获取单选按钮的值- checked属性没有被检测到。
  2. 通过在打字稿中定义model来使用model.function读取值。显然,无法访问model变量!
  3. 尝试使用[(ngModel)] -也不工作。

请建议转机

模板:

<input type="radio" id="options1" [(ngModel)]="myRadio" value="create">
<input type="radio" id="options2" [(ngModel)]="myRadio" value="continue">
然后在你的组件中定义一个myRadio变量,并像这样初始化它:myRadio: string = ''

这个变量将得到选择的值。

使用javascript来控制Angular2中的DOM元素,这违背了Angular2的理念

如果你只有2或3个单选项,你最简单的选择是使用模板引用变量,如下所示:

<input #op1 type="radio" id="options1" name="function" value="create">
<input #op2 type="radio" id="options2" name="function" value="continue">
<button (click)="fn(op1.checked ? op1.value : op2.checked ? op2.value)">Run</button>