我正在尝试使用反应式和formArray添加n个地址。我的第一个问题是,如何使用单选按钮选择一个地址作为主要地址?第二个问题是,当我从选择选项下拉列表中选择选项时,单选按钮的值也会更改。
我已经尝试通过添加(更改)事件绑定以编程方式更改单选按钮的值。
export class AppComponent {
public userForm: FormGroup;
constructor(private _fb: FormBuilder) {
this.userForm = this._fb.group({
firstName: [],
lastName: [],
address: this._fb.array([this.addAddressGroup()])
});
}
private addAddressGroup(): FormGroup {
return this._fb.group({
street: [],
city: [],
state: [],
category: ['home'],
isPrimary: [false, [Validators.required]]
});
}
get addressArray(): FormArray {
return <FormArray>this.userForm.get('address');
}
addAddress(): void {
this.addressArray.push(this.addAddressGroup());
}
onRadioChange(num) {
this.addressArray.value.forEach((address, index) => {
address.isPrimary = num === index;
});
}
}
<div formArrayName="address">
<div class="address-container" *ngFor="let group of addressArray.controls; let i = index;"
[formGroupName]="i">
<fieldset>
<legend>
<h3>Address: {{i + 1}}</h3>
</legend>
<mat-form-field>
<mat-label>Category</mat-label>
<mat-select
formControlName="category">
<mat-option value="home">home</mat-option>
<mat-option value="work">work</mat-option>
</mat-select>
</mat-form-field>
<br>
<mat-radio-group
formControlName="isPrimary"
name="isPrimary">
<mat-radio-button
[value]="true"
class="example-radio-button"
(change)="onRadioChange(i)">
Primary
</mat-radio-button>
</mat-radio-group>
<div>
<mat-form-field>
<input matInput placeholder="Street" formControlName="street">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="City" formControlName="city">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="State" formControlName="state">
</mat-form-field>
</div>
</fieldset>
</div>
</div>
<div class="form-row org-desc-parent-margin">
<button mat-raised-button (click)="addAddress()">Add more address</button>
</div>
如何复制: 1)添加其他地址 2)选择新地址作为主要地址 3)更改第一个地址的选择选项菜单的值 4)这会将单选按钮的值从false更改为true。
我非常感谢您的帮助。预先感谢。
答案 0 :(得分:0)
我进行了Stackblitz(尽管它在控制台中产生了错误)。以这种方式使用单选按钮也不容易,因为单选按钮具有2种状态。我建议使用复选框(如果不喜欢复选框的外观,则将其设置为单选按钮。)
请尝试以下操作:
在您的组件中:
export class RadioOverviewExample {
isPrimaryAddress: number | null = null;
...
onRadioChange(num) {
this.isPrimaryAddress = num;
}
}
在您的模板中:
<mat-radio-group formControlName="isPrimary" name="isPrimary">
<mat-checkbox
[checked]="isPrimaryAddress === i"
class="example-radio-button"
(change)="onRadioChange(i); isPrimaryAddress = i">
Primary
</mat-checkbox >
</mat-radio-group>