我想知道在 Angular 组件中为可选属性设置默认值的“Angular/Typescript 方式”是什么?当传递给可选属性的值是 null
时,我遇到了麻烦或 undefined
.
目前我有这样的事情:
export class FooComponent implements OnInit {
@Input() foo = 'foo';
@Input() bar = 0;
@Input() baz?: string;
}
如果声明默认值,则不必指定类型,因为它是指定值的类型,默认情况下属性是可选的。
bar
就是这种情况和 foo
特性。或者,您可以使用
?
标记此属性是可选的,但您不能声明其默认值。 baz
就是这种情况属性(property)。现在让我们看看当您将不同的值传递给这些属性时会发生什么。
<app-foo-component
[foo]
[bar]="null"
[baz]="undefined"
>
</app-foo-component>
如果我控制台记录这些属性,这就是我得到的:
foo
将正确 'foo'
bar
将是 null
baz
将是 undefined
当传递的值为空/未定义时,是否有一种优雅的方法也可以设置默认值,或者我是否需要像这样在 OnInit 中进行一些检查?
OnInit() {
this.bar = this.bar || 0;
}
感觉有一些方法可以做到这一点。对我来说,可选属性意味着值可能丢失、为空或未设置,但是当我想设置默认值时,它仅在属性丢失或为空时才有效。在这些情况下,它仍然将 value 设置为 null 或 undefined,这似乎令人困惑。
最佳答案
Here is the PROPER best solution for this. (ANGULAR 7,8, 9)
寻址方案 : 设置 @Input 变量的默认值 .如果没有值传递给该输入变量,则它将采用默认值。
例子:
我有一个名为 car 的对象接口(interface):
export interface car {
isCar?: boolean;
wheels?: number;
engine?: string;
engineType?: string;
}
您制作了一个名为 的组件应用车您需要使用 传递汽车的属性的地方@input Angular 装饰器 .但你想要那个 isCar 和 车轮 属性必须有一个默认值(即.. isCar: true,wheels: 4)
您可以按照以下代码为该对象设置默认值:
export class CarComponent implements OnInit {
private _defaultCar: car = {
// default isCar is true
isCar: true,
// default wheels will be 4
wheels: 4
};
@Input() newCar: car = {};
constructor() {}
ngOnInit(): void {
// this will concate both the objects and the object declared later (ie.. ...this.newCar )
// will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT
this.newCar = { ...this._defaultCar, ...this.newCar };
// console.log(this.newCar);
}
}
更详细的文章请引用 this .
引用 Destructuring assignment从这里
关于Angular - 如何为可选输入属性设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56005848/