【问题标题】:Angular 7: How to reset few checkboxes (generated dynamically using *ngFor) to it's previous state only click of a buttonAngular 7:如何将几个复选框(使用 *ngFor 动态生成)重置为之前的状态,只需单击一个按钮
【发布时间】:2020-09-27 19:25:22
【问题描述】:

我有一个子组件,它由 3 个复选框(使用 ngFor 动态生成)和一个应用和取消按钮组成。

子的选择器标签被添加到父模板中。父组件使用@ViewChild 访问该子组件,并调用子组件公开的present() 方法,并使用如下对象作为参数,该对象由复选框的选中状态组成。

每次显示模态时,都会调用 present() 方法。 UI/复选框第一次作为父级发送的值进行更新/检查。但是,在随后对 present() 的调用中,即使 options.checked 值在 ts 文件中按预期更新,这也不会反映在 UI 中。每次显示模式时,我都希望根据 parent 在 present() 方法中发送的值来选中或取消选中复选框。需要帮忙。提前致谢

parent.component.ts:

@ViewChild(childModalComponent) childModalComponent: ChildModalComponent;

onBtnClick() {
 this.childModalComponent.present({
  checkbox1: true,
  checkbox2: false,
  checkbox3: false
 });
}

parent.component.html:

<feature-child-modal></feature-child-modal>

child.component.ts:

 @ViewChild('childModal') childModal: ElementRef;

 ngOnInit() {
    this.options = [
     {
       label: 'label1',
       value: 'value1',
       checked: false,
     },
     {
       label: 'label2',
       value: 'value2',
       checked: false,
     },
     {
       label: 'label3',
       value: 'value3',
       checked: false,
     },
  ];
 }

present(optionsState: CompressTransactionType) {
  this.options.forEach(item => {
    if(item.value == "value1"){
      item.checked = optionsState.checkbox1;
    }

    if(item.value == "value2"){
      item.checked = optionsState.checkbox2;
    }

    if(item.value == "value3"){
      item.checked = optionsState.checkbox3;
    }
  });

  this.childModal.nativeElement.present();
}

dismiss() {
  this.childModal.nativeElement.dismiss();
}

child.component.html:

    <div *ngFor="let option of options">
      <input
          type="checkbox"
          [value]="option.value"
          (change)="onOptionsSelectChanged($event)"
          [checked]="option.checked" />
    </div>

【问题讨论】:

  • 首先使用 '===' 然后检查你的代码是否真的进入了 if 块
  • @ploofah,是的,它在 if 块内,并且值按预期设置。但它没有反映在 UI 中
  • 请检查复选框中名为标签的属性...不要认为复选框有一个
  • @NithinP.H 标签工作正常。在我的代码中,我使用的是自定义组件,因此它可以正常工作。

标签: javascript angular typescript checkbox angular7


【解决方案1】:

尝试在此处传递数组对象 option 而不是 $event。看看这个网址..

https://stackblitz.com/edit/angular-ivy-wifdeg

【讨论】:

  • 我的问题不在于点击事件,我在 present() 方法中遇到问题。 present 方法在 Parent 组件中被调用,并发送一个带有复选框值的参数。根据父组件发送的这个值,每次呈现子模态组件时都需要选中/取消选中子组件的复选框。
  • 抱歉要求有错误...请立即查看网址
猜你喜欢
  • 2021-05-15
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多