动态添加和删除angular 2自定义子组件中的formGroup

Pal*_*diN 5 angular2-forms angular2-template angular

我有一个自定义开关,需要使用和不使用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>
Run Code Online (Sandbox Code Playgroud)

定制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
    }
}
Run Code Online (Sandbox Code Playgroud)

从父组件我调用表单子组件的组件为:

<custom-switch [parentGroup]="form" [switchName]="'switch'"></custom-switch>
Run Code Online (Sandbox Code Playgroud)

我想用:

<custom-switch></custom-switch>
Run Code Online (Sandbox Code Playgroud)

并删除

[formGroup]="parentGroup"formControlName="{{ switchName }}"

对于非形式子组件.

我怎么能动态删除formGroupformControlName?因为当我尝试在非表单组件上使用它时会产生错误.

Gün*_*uer 4

无法有条件地添加/删除绑定。只能通过条件来控制向 DOM 添加属性。

您可以使用*ngIf在两个元素之间进行切换,其中一个元素具有绑定,而另一个元素没有绑定:

<custom-switch *ngIf="useForm" [parentGroup]="form" [switchName]="'switch'"></custom-switch>
<custom-switch *ngIf="!useForm"></custom-switch>
Run Code Online (Sandbox Code Playgroud)