【问题标题】:Reading radio button value - Angular 2读取单选按钮值 - Angular 2
【发布时间】:2016-09-19 17:55:20
【问题描述】:

我正在尝试读取单选按钮的值 - 角度为 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. 使用 document.getElementById 获取打字稿文件中单选按钮的值 - 未检测到属性 checked
  2. 通过在打字稿中定义model 来使用model.function 读取值。显然无法访问model 变量!
  3. 尝试使用 [(ngModel)] - 也没有用。

请为此提出周转建议。

【问题讨论】:

    标签: javascript html templates angular


    【解决方案1】:

    模板:

    <input type="radio" id="options1" [(ngModel)]="myRadio" value="create">
    <input type="radio" id="options2" [(ngModel)]="myRadio" value="continue">
    

    然后在你的组件中定义一个myRadio 变量并像这样初始化它: myRadio: string = ''

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

    并且,不要在 Angular2 中使用 javascript 来控制 DOM 元素,这违背了 angular2 的理念

    【讨论】:

    • 我按照建议尝试了,但我收到了一个显示 Cannot read property 'value' of undefined 的 html 错误。另外,如果我不应该使用 Javascript 修改 DOM 元素,建议我如何使用 Angular 2 做到这一点。
    • 您需要在组件的构造函数中初始化变量:myRadio: string = ''
    • (或输入默认值,例如myRadio: string = 'create'
    • Angular 2 很酷。不像老式的 javascript,我不需要做太多的编码。
    【解决方案2】:

    如果您只有 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>
    

    【讨论】:

      猜你喜欢
      • 2018-04-11
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2019-08-18
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      相关资源
      最近更新 更多