Angular语言 - 是否可以执行一个开关语句而不是多个 @Input()?



我正在以以下形式将一个属性传递到我的 Angular 组件中:

<my-component myAttribute></my-component>

为了更改组件中确定 CSS 的变量widthheight.

我还建立了预定义的属性值,以便输入:

<my-component large>

widthheight变量设置为等于100(处理后为 100px(。

但是,我很好奇我是否可以以一种不会有很多单独@Input()的方式编写多个@Input()条件,也许使用可以完成相同工作的 switch 语句?

我已经尝试了一点,但只在代码下收到了一片红色波浪线的海洋。

我的输入

size = 50 // Default value
@Input('small') set small(value) {
this.size = !value ? 25 : this.size;
}
@Input('medium') set medium(value) {
this.size = !value ? 50 : this.size;
}
@Input('large') set large(value) {
this.size = !value ? 100 : this.size;
}
@Input('x-large') set xlarge(value) {
this.size = !value ? 200 : this.size;
}

有一种方法,但它是...非传统的。我只能执行它,我不能告诉你是否应该使用它。因此,请尝试自担风险。

此方法(您可以在此处找到工作(摆脱了输入并使用组件的根元素:

export class HelloComponent {
size = '120';
attributes = {
'x-small': 50,
'small': 75,
'medium': 100,
'large': 125,
'x-large': 150,
};
constructor(
private el: ElementRef<HTMLElement>
) { }
ngOnInit() {
this.setSize();
}
private setSize() {
const attr = Object.keys(this.attributes).forEach(attr => {
const hasAttribute = this.el.nativeElement.hasAttribute(attr);
this.size = hasAttribute && this.attributes[attr] || this.size;
});
}
getSize() {
const myStyle = {
width: this.size + 'px',
height: this.size + 'px'
};
return myStyle;
}
}

它所做的基本上是尝试查找属性对象中列出的属性,如果找到它,则设置与该属性对应的值。

编辑创建私有函数时,它们只能在组件本身(某种(上访问。这意味着它们不会对其他组件产生副作用,也不需要真正进行测试。

例如,您可以测试这样的大小

it('should be 100px wide when setSize', () => {
component['el'].nativeElement.setAttribute('medium', '');
component.setSize();
expect(component.size).toEqual(100);
});

它被称为实现细节:这有点像我之前告诉你的:你的setSize函数现在是抽象的,你假设它工作,你测试当你调用它时,你的大小正在有效地改变。

这意味着您不必测试setSize函数的内部,只需测试它的行为相应

!但是你必须测试所有的可能性来防止副作用:例如,如果属性不是medium,而是exxxtra-large,会发生什么?这是您需要测试的情况。

这应该加快您的测试!

将输入作为对象而不是数字传递。然后,您可以使用以下任一方法截获传递的值:

二传手(根据您当前的尝试(或

https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter

纳恩变化

https://angular.io/guide/component-interaction#intercept-input-property-changes-with-ngonchanges

使用资源库,假设维度是传入的对象,您可以执行以下操作:

private _width = 0;
private _height = 0;
@Input()
set dimensions(dimensions: any) {
this._width = dimensions.width
this._height = dimensions.height
// could put a switch case here
}
get width(): string { return this._width; }
get height(): string { return this._height; }

您可以控制和计算父组件中子组件的大小,并发送具有变量属性的对象。计算完后,您可以通过 1 个输入接收此值,例如size

父组件

<my-component size="this.childSize"></my-component>

子组件

private _size: any;
@Input('size') set size(value) {
this._size = value;
const property = Object.keys(this.size)[0]; // expecting only 1 property
switch (property):
case 'small':
// do something
console.log(this.size[property]);
break;
case 'large':
// do something
break;
default:
// do something
}
public get size(): any {
return this._size;
}

当然,你应该为childSize创建自己的类型,以指示和限制可能存在的属性。示例,您可以发送的对象。.

{
small: 15
}
{
large: 35
}

最新更新