首页 文章

在Angular 5中与子组件内的@Input绑定时,Checkbox 's checked status doesn't会更新

提问于
浏览
0

我正在尝试在子组件内部渲染复选框,并根据复选框选中或不显示一些文本 .

根据来自父组件的输入属性值(选中)选中或取消选中复选框 .

<input #checkInput type="checkbox" [checked]="checked" />

并使用以下代码显示活动或禁用的文本 .

<span>
    <ng-container *ngIf="checkInput.checked">Active</ng-container>
    <ng-container *ngIf="!checkInput.checked">Disabled</ng-container>
</span>

父组件数据来自API . 因此,为了模拟一些延迟,我在setTimeout中包装并在父组件内部渲染表 . 表行包含子组件选择器,如下所示 .

<tbody>
      <tr *ngFor="let org of organisations">
        <td width="120px">{{org.id}}</td>
        <td>{{org.name}}</td>
        <td><app-child [checked]="org.active" checkedText="Active" uncheckedText="Disabled"></app-child></td>
        <td><a class="button secondary">Edit</a></td>
      </tr>
    </tbody>

我的期望是,如果'checked'属性为true,从父组件到子组件,则子组件内复选框旁边的文本应显示为'active'而不是'disabled' . 但是,它没有发生 . 最初加载时显示“已禁用” .

我已经创建了一个用于演示行为的plunker . 任何人都可以让我知道为什么即使选中复选框,初始加载的文本也会被禁用?

plunker链接:https://plnkr.co/edit/mqmVYdbMF9qGduQYLYXa?p=preview

谢谢 .

1 回答

  • 1

    输入元素 [checked]@Input 不一样, [checked] 的值被更改时不会触发 Change Detection .

    Solution 1:
    您可以更改为使用 [(ngModel)] 而不是 [checked] 来解决问题 .

    <input #checkInput type="checkbox" [(ngModel)]="checked" />
    <span>
      <ng-container *ngIf="checkInput.checked">{{checkedText}}</ng-container>
      <ng-container *ngIf="!checkInput.checked">{{uncheckedText}}</ng-container>
    </span>
    

    Solution2:
    AfterViewInit 生命挂钩上手动触发 change detection ,同时仍然使用 [checked] .

    import {AfterViewInit, ChangeDetectorRef} from '@angular/core'
    
    export class ChildComponent implements AfterViewInit {
      constructor(private cd: ChangeDetectorRef) { }
    
      ngAfterViewInit() {
        this.cd.detectChanges();
      }
    }
    

相关问题