2016-09-19 40 views
4

我想讀的單選按鈕值 - 在角2,閱讀單選按鈕值 - 角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)] - 也沒有工作。

請爲此建議一個週轉。

回答

4

模板:

<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理念

+0

我試過的建議,但我發現了,說'不能讀取屬性「值」一個HTML錯誤未定義的。另外,如果我不應該使用Javascript修改DOM元素,建議我如何使用Angular 2來做到這一點。 –

+0

你需要在你的組件的構造函數中初始化變量: 'myRadio:string =''' –

+0

(或者把默認值例如'myRadio:string ='create'') –