2017-11-11 166 views
0

我建立一個用戶接口,其中用戶可以創建兩種類型的內容即LINKMESSAGE與無線電輸入結合使用`ngModel`顯示或隱藏部

我會使用內置解決方案,例如Ionic中的Segment組件,但由於設計要求,這是不可能的。

我做的是什麼,我有兩個無線電輸入

<input [(ngModel)]="notificationCreateType" type="radio" id="notification_type_link" name="notificationType" value="0" class="custom-radio" /> 

<input [(ngModel)]="notificationCreateType" checked type="radio" id="notification_type_message" name="notificationType" value="1" class="custom-radio" /> 

值0的鏈路和1是消息。

  <div *ngIf="notificationCreateType == '0'"> 
       ... stuffs here 
      </div> 


      <div *ngIf="notificationCreateType == '1'"> 
       ... stuffs here 
      </div> 

似乎選擇任意的無線選項時,工作正常,但是當已經被選中的頁面加載和無線選項最初不工作。

[(ngModel)]="notificationCreateType"絕對使用無線電輸入的值,並設置notificationCreateType它,雖然它不會做同樣的當輸入已經被設置checked屬性

什麼我會檢查喜歡做的是要麼ngModel尊重輸入的checked屬性,或者甚至更好的是我可以在組件的ts文件中設置notificationCreateType的初始值,該文件用於在模板中自動檢查無線電輸入。

這是甚至可能的,因爲我經歷了許多文檔,包括官方的Ionic和Angular文檔,仍然沒有發現關於無線電輸入的詳細信息。

回答

1

從模板中刪除checked屬性。這是無用的,因爲Angular將用起始值notificationCreateType覆蓋選中的值。所以,你會只是有

<input [(ngModel)]="notificationCreateType" type="radio" 
     name="notificationType" value="0"/> 

<input [(ngModel)]="notificationCreateType" type="radio" 
     name="notificationType" value="1"/> 

然後在組件類,只需設置初始值:

public notificationCreateType = '1'; 

角將檢查默認的單選按鈕,你的照顧。

+0

哇!這工作非常漂亮。 我排除'公共'關鍵字,仍然工作,我希望這不會在未來造成任何問題。 謝謝! –

+1

除非指定'private',否則假定'public',所以我認爲它不會引起問題。 – BeetleJuice