为了更轻松地使用我的 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}"/>
是一种后备解决方案,但我的问题涉及使用单独的输入
您可以使用
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);