Angular 组件中是否可以有条件/相关输入参数?

问题描述 投票:0回答:1

为了更轻松地使用我的 Angular 组件,我想只允许组件上的相关输入。这可能吗? IE。对于我的组件

elevensies
想要希望这样工作:

<elevensies [drink]="tea" [milk]="yes" />

<elevensies [drink]="water"/>

但是允许组合:

<elevensies [drink]="water" [milk]="yes" />// Is it possible to give an error when adding "milk" to water?

这可能吗? 注意:使用

<elevensies [oneInputToRuleThemAll]="{drink=tea,milk=yes}"/>
是一种后备解决方案,但我的问题涉及使用单独的输入

angular validation input
1个回答
0
投票

您可以使用

effect
input
信号对输入参数做出反应,并使用
throw new Error(' ... ')
抛出错误,这将迫使用户修复错误。

...
export class Elevensies {
  drink: InputSignal<'tea' | 'water'> = input.required();
  milk: InputSignal<'yes' | 'no'> = input<'yes' | 'no'>('no');

  constructor() {
    effect(() => {
      if (this.drink() !== 'water' && this.milk() !== 'no') {
        throw new Error(
          "Tea can only have milk set as 'yes' as a parameter, so leave milk as no or empty"
        );
      }
    });
  }
}

完整代码:

import { Component, input, InputSignal, effect } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';

    @Component({
      selector: 'elevensies',
      standalone: true,
      template: `
        <h1> {{ drink() }}</h1>
      `,
    })
    export class Elevensies {
      drink: InputSignal<'tea' | 'water'> = input.required();
      milk: InputSignal<'yes' | 'no'> = input<'yes' | 'no'>('no');

      constructor() {
        effect(() => {
          if (this.drink() !== 'water' && this.milk() !== 'no') {
            throw new Error(
              "Tea can only have milk set as 'yes' as a parameter, so leave milk as no or empty"
            );
          }
        });
      }
    }

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [Elevensies],
  template: `
    <elevensies [drink]="'tea'" [milk]="'yes'" />
    <elevensies [drink]="'water'"/>
    <elevensies [drink]="'water'" [milk]="'yes'" /> <!-- should throw error -->
  `,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.