加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:36:02 所属栏目:安全 来源:网络整理
导读:我有一个自定义开关,需要用于有和没有形式. 即 定制switch.component.html div class="custom-switch" [formGroup]="parentGroup" input id="{{ id }}" name="status" type="checkbox" [checked]="checked" formControlName="{{ switchName }}" (change)="on
我有一个自定义开关,需要用于有和没有形式.

定制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?因为当我尝试在非表单组件上使用它时会产生错误.

解决方法

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

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

<custom-switch *ngIf="useForm" [parentGroup]="form" [switchName]="'switch'"></custom-switch>
<custom-switch *ngIf="!useForm"></custom-switch>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读