【问题标题】:I want to if I select Year Radio button, select opeion value 2018 selected, now no one selected如果我选择年份单选按钮,我想选择 opeion value 2018 selected,现在没有选择
【发布时间】:2018-08-07 22:08:24
【问题描述】:

如果我选择年份单选按钮,我想选择 opeion value 2018 selected,现在没有选择。

类代码是:

alls:string='';
type:string ='1';
yData = [{"Year":2018},{"Year":2017},{"Year":2016}]`enter code here`

这是模板代码:

<div>
            <div class="radio">
                <label><input type="radio" [(ngModel)]="type" name="type" value="1">All Search</label>
            </div>
            <div class="radio">
                <label><input type="radio" [(ngModel)]="type" name="type" value="2">Album Title </label>
            </div>
            <div class="radio">
                <label><input type="radio" [(ngModel)]="type" name="type" value="3">Year </label>
            </div>
            <div class="radio">
                <label><input type="radio" [(ngModel)]="type" name="type" value="4">Event Date </label>
            </div>
            <div class="radio">
            <label><input type="radio" [(ngModel)]="type" name="type" value="5">Description </label>
            </div>

    </div>


<div *ngIf="type === '1'">All Search:<input type="text" [(ngModel)]="alls" /><br></div>
<div *ngIf="type === '2'">Album Title: {{this.type}} <input type="text" [(ngModel)]="alls" /></div>
<div *ngIf="type === '3'">Year: {{this.type}} alls {{yData[0]["Year"]}}
<select [(ngModel)]="alls">
<option *ngFor="let yrow of yData" [value]="yrow.Year"> {{yrow.Year}} </option>
</select>
</div>
<div *ngIf="type === '4'">Event Date: {{this.type}} <input type="date" [(ngModel)]="alls" /></div>
<div *ngIf="type === '5'">Description:  {{this.type}}  <input type="text" [(ngModel)]="alls" /></div>

如上 Angular 5 代码。

【问题讨论】:

  • 如果您选择 2018 选项?那么你期望发生什么?
  • 好吧,你的选择的 ngModel(保存选择的值)是alls。它的值为''。为什么会选择 2018 年?
  • 先生,有两个块,一个用于单选按钮,另一个用于显示输入控件,这与单选按钮相关,例如如果 'type' 值等于 3 则将显示年份选择控件,即工作完美,但在选择控件中数据来自 yData,(来自 http.get().subscribe()),但我需要在选择选项中默认值应该是 2018(第一个索引)。我希望你明白我需要什么。

标签: angular angular2-forms angular5


【解决方案1】:

如果你改变“类型”,你必须告诉 Angular 会发生什么。因此,您必须“分离”ngModel 和 ngModelChange。如果你使用简单的 [(ngModel)] 你只能改变变量“类型”

<input type="radio" value="3" [ngModel]="type" 
           (ngModelChange)="type = 3;alls=yData[0].Year">

实现相同目的的其他方法是使用 getter setter 并使用 [(ngModel)]

在您的 .ts 中

_type:number;
get type(){
   return _type;
}
set type(value:any)
{
   this._type=value;
   if (this._type==3)
      this.alls=this.yData[0].Year
}

其他方式是使用响应式表单并更改,请参阅https://angular.io/guide/reactive-forms#reactive-forms

【讨论】:

  • 不,先生,我需要在选择的下拉选项中设置默认值。数据来了,但拳头是空白的。我点击选择然后我可以设置任何值。但我需要选定的属性来处理简单的 html...
猜你喜欢
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多