以下是的类型定义
input.required
required: {
/** Declares a required input of type `T`. */
<T>(opts?: InputOptionsWithoutTransform<T>): InputSignal<T>;
/**
* Declares a required input of type `T` with a transform function.
*
* The input accepts values of type `TransformT` and the given
* transform function will transform the value to type `T`.
*/
<T, TransformT>(opts: InputOptionsWithTransform<T, TransformT>): InputSignalWithTransform<T, TransformT>;
};
如果你注意到了,我们得到了第一种
InputOptionsWithoutTransform
因为我们只为定义了一个类型
<T>
(
{ id?: number; title?: string }
)这导致它使用第一个,而不是我们设置的,两者
<T, TransformT>
(
<InputRequiredCustomType, InputRequiredCustomType>
)它将采用第二种类型,转换将可用!
我们可以添加属性
alias
在我们定义转换的同一个地方,它非常有效!
import { CommonModule } from '@angular/common';
import { Component, booleanAttribute, input, output } from '@angular/core';
export type InputRequiredCustomType = { id?: number; title?: string }; // <- changed here
@Component({
selector: 'app-each-post',
standalone: true,
template: `
<h1>{{post()?.title}}</h1>
<button (click)="onPost()">Action</button>
`,
imports: [CommonModule],
})
export class EachPostComponent {
// where to add alias when using input.required
post = input.required<InputRequiredCustomType, InputRequiredCustomType>({ // <- changed here
alias: 'asdf',// <- changed here
transform: this.transformMe,
});
// post = input({}, { transform: this.transformMe });
onAction = output<{ id?: number; title?: string }>();
transformMe(value: any) {
return { ...value, title: 'my override title' };
}
onPost() {
this.onAction.emit(this.post());
}
}
Stackblitz Demo