代码之家  ›  专栏  ›  技术社区  ›  ttugates

如何在基于父组件的子组件的元素上实现*ngIf/disabled

  •  0
  • ttugates  · 技术社区  · 7 年前

    父组件标记:

    <full-screen-dialog-header (onClickPrimaryAction)="onClickSaveCustomer()"
      (primaryActionDisabled)="*ngIf=customerFormGroup.enabled && !customerFormGroup.valid">
    </full-screen-dialog-header>
    

    子组件:

    export class FullScreenDialogHeaderComponent {
    
      @Input() primaryActionDisabled: Observable<boolean>;
      @Output() onClickPrimaryAction = new EventEmitter();
    
      public onClickPrimaryActionEvent($event) {
        this.onClickPrimaryAction.emit($event);
      }
    }
    

    子标记

    ...
    <button mat-button (click)="onClickPrimaryActionEvent($event)" 
    [disabled]="primaryActionDisabled">{{primaryActionText}}</button>
    ...
    

    我正在努力 @Input() primaryActionDisabled: Observable<boolean> 工作。

    我的问题和预期行为是:

    • 在父标记中 (primaryActionDisabled)="!customerFormGroup.valid" -我希望孩子的primaryActionDisabled包含以下结果的可观察值: !customerFormGroup.valid
    1 回复  |  直到 7 年前
        1
  •  1
  •   Martin Adámek    7 年前

    首先,当使用 @Input 装饰师,你应该使用 [primaryActionDisabled] 结合

    然后你需要传递可观察的,而不是表达式:

    // in parent controller
    primaryActionDisabled$ = new BehaviorSubject<boolean>(true); // disabled by default
    
    // in parent template
    <full-screen-dialog-header 
        (onClickPrimaryAction)="onClickSaveCustomer()"
        [primaryActionDisabled]="primaryActionDisabled$">
    </full-screen-dialog-header>
    

    primaryActionDisabled$.next(newBoolValue); 每次值都应该更改(因此每次表达式 customerFormGroup.enabled && !customerFormGroup.valid

    最后,在您的子组件中,使用异步管道来处理该可观察值:

    <button mat-button 
            (click)="onClickPrimaryActionEvent($event)" 
            [disabled]="primaryActionDisabled | async">{{ primaryActionText }}</button>