Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了动态添加和删除angular 2自定义子组件中的formGroup大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个自定义开关,需要用于有和没有形式.

定制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>

大佬总结

以上是大佬教程为你收集整理的动态添加和删除angular 2自定义子组件中的formGroup全部内容,希望文章能够帮你解决动态添加和删除angular 2自定义子组件中的formGroup所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: