代码之家  ›  专栏  ›  技术社区  ›  Indraraj26

角度信号变换不适用于输入。必需

  •  1
  • Indraraj26  · 技术社区  · 2 年前

    如果我用声明 input.required({transform: this.transformMe}) 然后我得到

    Type '(value: any) => any' is not assignable to type 'undefined'.(2322)

    但是如果我声明 input({}, {transform: this.transformMe}) 那么它运行良好。

    以及如何提供 alias 在里面 input.required()

    Playground-Link

    1 回复  |  直到 2 年前
        1
  •  0
  •   Naren Murali    2 年前

    以下是的类型定义 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

    推荐文章