我正在制作 Angular 6 应用程序,其中使用的是 Angular React 形式。
HTML:
<form [formGroup]="form">
<h2>Click the add button below</h2>
<button (click)="addCreds()">Add</button>
<div formArrayName="credentials" *ngFor="let creds of form.controls.credentials?.value; let i = index">
<div [formGroupName]="i" style="display: flex">
<select (ngModelChange)="changeAction($event)" formControlName="action">
<option *ngFor="let option of options" value="{{option.key}}"> {{option.value}} </option>
</select>
<input placeholder="Name" formControlName="name">
<div *ngIf="showLabel">
<input placeholder="Label" formControlName="label">
</div>
</div>
</div>
</form>
<pre>
{{ form ?.value | json }}
</pre>
T:
form: FormGroup;
showLabel: boolean = false;
options : any = [
{ "key" : "set", "value": "Set" },
{ "key" : "wait", "value": "Wait" },
{ "key" : "go", "value": "Go" }
]
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
credentials: this.fb.array([]),
});
}
addCreds() {
const creds = this.form.controls.credentials as FormArray;
creds.push(this.fb.group({
action: '',
name: '',
label: ''
}));
}
changeAction(e) {
if(e === "set" || e === "go") {
this.showLabel = true;
} else {
this.showLabel = false;
}
}
工作堆栈 Blitz : https://stackblitz.com/edit/angular-form-array-example-yksojj
在这个给定的示例中,将有一个添加按钮,单击该按钮后,您将获得一个选择框
,其值为set、wait、go
和一个输入称为名称。单击添加按钮后,将添加同一行并形成数组内的每个对象。
您还可以在标签的 html 中看到 if
条件,
<div *ngIf="showLabel">
<input placeholder="Label" formControlName="label">
</div>
我需要的东西在选择框中,如果我选择设置或继续,那么标签需要显示,否则不应该显示它已写,
changeAction(e) {
if(e === "set" || e === "go") {
this.showLabel = true;
} else {
this.showLabel = false;
}
}
足够清楚如果用户点击三次添加按钮,则下拉列表和名称字段单独需要显示三次,而如果用户从下拉列表中选择值作为设置或 go 那么标签输入需要显示到单独的特定行,其中下拉列表已设置值并 go。如果选择是等待
,那么下拉值为 wait
的行不应有标签框。
请帮助我达到预期的结果..
最佳答案
如果您将disabled:true属性添加到formControl,它将从formGroup中排除fromControl,然后您可以手动启用formControl
creds.push(this.fb.group({
action: '',
name: '',
label: {disabled:true, value: ""}
}));
然后使用enable方法启用
changeAction(e,index) {
if(e === "set" || e === "go") {
this.showLabel = true;
this.form.get('credentials').at(index).get('label').enable();
} else {
this.showLabel = false;
this.form.get('credentials').at(index).get('label').disable();
}
}
示例:https://stackblitz.com/edit/angular-form-array-example-5buwyr
关于javascript - 以 Angular react 形式显示条件输入框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53934061/