在角度4中,我有一个组件,我获取用户已保存的表单字段的数据。所以基本上我得到这样的数据
data = [
{type: "option", label: "Country", options: "India, Sri Lanka"},
{type: "option", label: "Size", options: "Large, Small, Extra Large"},
{type: "radio", label: "Gender", options: "Male, Female"}
]
现在我想在html中使用这些数据并构建表单。因此,当type
为option
时,它将是包含这些选项的选择选项类型。如果它的类型为radio
,那么它将在表格中显示带有这些选项的无线电字段(男性,女性)
我已经制作了这样的组件
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-registration-checkout',
templateUrl: './registration-checkout.component.html',
styleUrls: ['./registration-checkout.component.css']
})
export class RegistrationCheckoutComponent implements OnInit {
id: any;
constructor(
private http: HttpClient,
protected checkOutService: CheckoutService,
) {
}
ngOnInit() {
this.id = localStorage.getItem('id');
this.checkOutService.getExtraFields(this.id).subscribe( response => {
this.fields = response['fields'];
console.log(this.fields); // shows data in array object
},
err => {
console.log(err);
});
}
}
在HTML中我已经制作了像这样的代码
<div *ngFor = "let form of fields; let i = index">
{{form | json}}
<div *ngIf="form.type=='option'">
Show Select Option
{{form.options}}
<select>
<option></option>
</select>
</div>
<div *ngIf="form.type=='radio'">
show Radio Option
<input type="radio" name="">
</div>
这里我有点困惑如何为select into循环做出选项。我的意思是选项现在是逗号的字符串。那么我怎么能这样做它看起来像
<select name="country">
<option value="India">India</option>
<option value="Sri Lanka">Sri Lanka</option>
</select>
答案 0 :(得分:1)
尝试 like this
<div *ngFor="let form of fields; let i = index">
<div *ngIf="form.type === 'option'">
<select>
<option *ngFor="let option of form.options.split(',')" [value]="option">{{ option }}</option>
</select>
</div>
<div *ngIf="form.type === 'radio'">
<ng-container *ngFor="let option of form.options.split(',')">
<input type="radio" [name]="option"> {{ option }}
</ng-container>
</div>