如何在 child 组件的元素上实现 *ngIf/disabled,基于 parent 组件

How to implement *ngIf/disabled on element of child component, predicated on parent component

Parent 组件标记:

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

Child 分量:

export class FullScreenDialogHeaderComponent {

  @Input() primaryActionDisabled: Observable<boolean>;
  @Output() onClickPrimaryAction = new EventEmitter();

  public onClickPrimaryActionEvent($event) {
    this.onClickPrimaryAction.emit($event);
  }
}

Child 标记

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

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

我的问题和预期行为是:

首先,在使用@Input装饰器时,应该使用[primaryActionDisabled]绑定。

然后你需要在那里传递 observable,而不是表达式:

// 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>