在 angular 2 自定义子组件中动态添加和删除 formGroup
dynamically add and remove formGroup in angular 2 custom child component
我有一个自定义开关,需要在有和没有 forms
的情况下使用。
即
自定义-switch.component.html
<div class="custom-switch" [formGroup]="parentGroup">
<input id="{{ id }}" name="status" type="checkbox"
[checked]="checked"
formControlName="{{ switchName }}"
(change)="onChange($event, id)" />
<label for="{{ id }}" class="label-default" data-toggle="tooltip" data-selector="true"
data-title="Switch"></label>
</div>
自定义-switch.component.ts
import { Component, Input } from "@angular/core";
@Component({
selector : 'custom-switch',
template : 'custom-switch.component.html'
})
export class CustomSwitchComponent {
@Input('id') id : any = 'switch';
@Input('parentGroup') parentGroup : any;
@Input('switchName') switchName : any;
onChange() {
//do something
}
}
从父组件我将表单子组件的组件称为:
<custom-switch [parentGroup]="form" [switchName]="'switch'"></custom-switch>
我想使用:
<custom-switch></custom-switch>
并删除
[formGroup]="parentGroup"
和
formControlName="{{ switchName }}"
对于非表单子组件。
如何动态删除 formGroup
和 formControlName
?当我尝试在非表单组件上使用它时它会产生错误。
无法有条件地 add/remove 绑定。只有给DOM添加属性才可以通过条件来控制
您可以使用 *ngIf
在一个有绑定而另一个没有绑定的两个元素之间切换:
<custom-switch *ngIf="useForm" [parentGroup]="form" [switchName]="'switch'"></custom-switch>
<custom-switch *ngIf="!useForm"></custom-switch>
我有一个自定义开关,需要在有和没有 forms
的情况下使用。
即
自定义-switch.component.html
<div class="custom-switch" [formGroup]="parentGroup">
<input id="{{ id }}" name="status" type="checkbox"
[checked]="checked"
formControlName="{{ switchName }}"
(change)="onChange($event, id)" />
<label for="{{ id }}" class="label-default" data-toggle="tooltip" data-selector="true"
data-title="Switch"></label>
</div>
自定义-switch.component.ts
import { Component, Input } from "@angular/core";
@Component({
selector : 'custom-switch',
template : 'custom-switch.component.html'
})
export class CustomSwitchComponent {
@Input('id') id : any = 'switch';
@Input('parentGroup') parentGroup : any;
@Input('switchName') switchName : any;
onChange() {
//do something
}
}
从父组件我将表单子组件的组件称为:
<custom-switch [parentGroup]="form" [switchName]="'switch'"></custom-switch>
我想使用:
<custom-switch></custom-switch>
并删除
[formGroup]="parentGroup"
和
formControlName="{{ switchName }}"
对于非表单子组件。
如何动态删除 formGroup
和 formControlName
?当我尝试在非表单组件上使用它时它会产生错误。
无法有条件地 add/remove 绑定。只有给DOM添加属性才可以通过条件来控制
您可以使用 *ngIf
在一个有绑定而另一个没有绑定的两个元素之间切换:
<custom-switch *ngIf="useForm" [parentGroup]="form" [switchName]="'switch'"></custom-switch>
<custom-switch *ngIf="!useForm"></custom-switch>