【问题标题】:How to set @Input variable as an optional in angular 5?如何在角度 5 中将 @Input 变量设置为可选?
【发布时间】:2020-05-19 15:56:33
【问题描述】:

我想设置@Input 参数可选。

例如:

Child1.html:

templateUrl:'common-html.html'

Child1.TS:

currentValue : boolean = true;

案例 2:

Child2.html:

templateUrl:'common-html.html'

Child2.TS:

// Not declared **currentValue**

Common-HTML.html:

<app-master [isLogEnabled]="currentValue"></app-master>

但上述更改在 AOT 时会出现错误:

类型 Child2.Component 上不存在属性“isLogEnabled”

所以我不能更改 HTML 的:

<app-master [isLogEnabled]="currentValue"></app-master>

【问题讨论】:

  • 你不能&lt;app-master&gt;&lt;/app-master&gt;
  • 其实那个HTML是作为一个集中的,所以我改不了
  • 这个问题目前还不清楚。但是回答“可选输入属性”的问题,可以在子组件中尝试isLogEnabled?: any
  • 添加了更多信息
  • 可能没有那么干净,但您可以传递一个带有可选属性的对象。

标签: javascript angular angular-decorator


【解决方案1】:

我愿意:

App-Master-Component.ts

@Input() isLogEnabled: boolean = false; // can change false to true, null or w.e. depending on what you want as the default
// if consumer passes in a value, it will be overridden

然后在 Child2.component.html 中

<app-master></app-master>

如果 Child2.component.ts 文件中不存在 currentValue,则无法绑定 [isLogEnabled]="currentValue"

【讨论】:

  • HTML 是通用的,所以我无法更改 HTML
【解决方案2】:

您不能提供未声明的财产。 但是你可以使用这样的东西:

<app-master [isLogEnabled]="currentValue || false"></app-master>

或者你可以在组件内部创建getter:

get isLogEnabled() {
    return this.isLogEnabled || false;
}

或者您可以尝试使用'?'

@Input() isLogEnabled?: boolean;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2020-03-15
    • 2019-03-14
    • 1970-01-01
    相关资源
    最近更新 更多