[英]Using object literal notation to set a property's value in terms of another property
[英]Set literal object to a component's Input property as a known object class
我有一個類型為Foo
的@Input
屬性的組件:
@Component({
...
})
export class MyComponent {
@Input() Options: Foo;
...
}
並在ParentComponent.html
文字類中將其作為輸入值傳遞給它:
<My [Options]="{prop1:true, prop2:false, prop3:1, ... }"></My>
然后, Options
類型不再是Foo
。 它更改為匿名對象,因此無法再訪問Foo
方法。
防止這種情況的一種方法是在ParentComponent .ts
創建Foo
的實例,並將其作為變量傳遞:
@Component({
...
})
export class ParentComponent {
Options: new Foo(true, true, 1, ...);
...
}
並在ParentComponent.html
使用:
<My [Foo]="options"></My>
另一種方法是以某種方式將匿名對象轉換為新創建的Foo
對象:
@Component({
...
})
export class MyComponent {
@Input() set Options(value: Foo){
//Somehow cast anonymous to Foo.
}
private options : Foo;
...
}
Foo
? 如果要使用所描述的兩種方法之一使用類方法,則有時需要使用new
創建類Foo
的實例。 如果要將普通對象作為@Input
,則輸入不能為(class-)類型的Foo
因為它不是該類的實例。 在該類中,您需要調用new Foo(fooInput)
,然后例如將新創建的實例分配給另一個成員變量。
我認為,最好將數據放在普通數據對象中而不是類中:為了類型安全,將Foo
定義為interface
而不是class
。 然后,將class
的方法放入FooService
,該操作可操作Foo
對象。 這樣,您就不必費心使用類實例化了。
class User {
constructor(public firstName: string, public lastName: string) {}
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
變成:
interface User {
firstName: string;
lastName: string;
}
class UserService {
getFullName(user: User): string {
return `${user.firstName} ${user.lastName}`;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.