我想知道为Angular组件中的可选属性设置默认值的“ Angular / Typescript方法”是什么?当传递给可选属性的值是null
或undefined
时,我会遇到麻烦。
目前,我有这样的事情:
export class FooComponent implements OnInit {
@Input() foo = 'foo';
@Input() bar = 0;
@Input() baz?: string;
}
如果声明默认值,则不必指定类型,因为它是分配值的类型,并且属性默认为可选。 bar
和foo
属性就是这种情况。
或者,您可以使用?
来标记此属性为可选属性,但不能声明其默认值。 baz
属性就是这种情况。
现在,让我们看看将不同的值传递给这些属性时会发生什么。
<app-foo-component
[foo]
[bar]="null"
[baz]="undefined"
>
</app-foo-component>
如果我控制台记录这些属性,这就是我得到的:
foo
将正确'foo'
bar
将是null
baz
将是undefined
当传递的值为null / undefined时,是否有一种优雅的方法还可以设置默认值?还是需要像这样在OnInit中进行检查?
OnInit() {
this.bar = this.bar || 0;
}
感觉有某种方法可以做到这一点。对我来说,可选属性意味着值可能会丢失,为null或未设置,但是当我要设置默认值时,它仅在缺少属性或为空时才起作用。在这种情况下,它仍将值设置为null或未定义,这似乎令人困惑。
答案 0 :(得分:3)
这是正确 最佳 解决方案。 (7,8,9角)
寻址解决方案:要为@Input变量设置默认值。如果没有值传递给该输入变量,则它将采用默认值。
示例:
我有一个名为car的对象接口:
IsDeleted
您制作了一个名为 app-car 的组件,您需要在其中使用 @angular输入装饰器 传递car的属性。但您希望 isCar 和 Wheels 属性必须具有默认值(即isCar:true,wheels:4)
您可以按照以下代码为该对象设置默认值:
export interface car {
isCar?: boolean;
wheels?: number;
engine?: string;
engineType?: string;
}
有关详细文章,请参见this。
答案 1 :(得分:1)
我有一些嵌套的子组件时遇到同样的问题。
最后这对我有用:
@Input()
public foo;
get fooWithDefault() {
return this.foo ?? 'any default value';
}
然后我在模板中使用了 fooWithDefault
属性而不是 foo
。
答案 2 :(得分:0)
您可以将Contact.includes(:books).count # 10 (SELECT COUNT(*) FROM "contacts")
Contact.includes(:books).where(books: {"id":[1,2] }).count # 5 (LEFT OUTER JOIN x2)
Contact.includes(:books).where.not(books: {"id":[1,2] }).count # 4 (LEFT OUTER JOIN x2)
# so same as you
# we can find who those missing contacts are:
ids = Contact.includes(:books).to_a.map(&:id) -
Contact.includes(:books).where(books: { id: [1, 2] }).to_a.map(&:id) -
Contact.includes(:books).where.not(books: { id: [1, 2] }).to_a.map(&:id)
# I'm getting 3 ids in my case
Contact.where(id: ids).map { |c| c.books.size }
# they all have 0 books
Contact.eager_load(:books).count # 10 (with LEFT OUTER JOIN x2)
# every contact with at least one book
Contact.includes(:books).where.not(books: { id: nil }).count
# some wrong queries
Contact.includes(:books).where(books: {"id":[1,2] }).or(
Contact.includes(:books).where(books: { id: nil })).size
# returns 8
Contact.includes(:books).where.not(books: {"id":[1,2] }).or(
Contact.includes(:books).where(books: { id: nil })).size
# returns 7
定义为getter / setter属性,并确保在必要时在setter中应用默认值:
bar
有关演示,请参见this stackblitz。