在某些上下文 Angular 17 中真的不可能在组件输入上设置默认值吗

问题描述 投票:0回答:1

我希望我错过了一些东西,但似乎在以下上下文中,不可能在

@Input
上设置默认值:

  • bindToComponentInputs
    在路由器模块配置中设置为 true
  • 输入值在 URL 中表示为查询参数
  • 父组件不不传入输入值

在这种情况下,这些方法都不会设置所需的默认值:

  • @Input() foo: string = 'bar'; // value is overridden with undefined
  • @Input( { transform: (val: string) => val ?? 'bar' }) foo: string;  // transform method is not called by change detection because parent didn't pass this Input value in

我们陷入困境,因为我们定义了很多输入默认值,但我们想打开

bindToComponentInputs
。但在这样做时,我们必须假设,如果 URL 中没有表示我们的默认值,它们将是未定义的。

请告诉我我错了!

angular
1个回答
0
投票

当您使用

@Input
时,请始终期待其值

没问题,使用 setter

  query!:string //<--define your variable "query"

  @Input('query') set _query(value:string){
    //see that always execute this even you don't indicate query
    console.log("I'm executing this")

    this.query=value||'query by defect'
  }
© www.soinside.com 2019 - 2024. All rights reserved.