【问题标题】:Angular 9 - Property Binding with undefinedAngular 9 - 未定义的属性绑定
【发布时间】:2020-07-01 09:05:46
【问题描述】:

我有一个名为 CustomTextBox 的组件

在我的 CustomTextBox.ts 中,写成

@Input('id') _id:string
@Input('class') _class:string

在我的CustomTextBox.htm中,通过使用属性绑定,写成

<textarea [id]="_id" [class]="_class"></textarea>

我可以从应用组件中将组件调用为以下任一选项

<CustomTextBox></CustomTextBox>
  <CustomTextBox id="sampleid"></CustomTextBox>
  <CustomTextBox class="sampleid"></CustomTextBox>

id 和 class 是可选的

但是当调用&lt;CustomTextBox&gt;&lt;/CustomTextBox&gt;时生成代码如下

<CustomTextBox id="undefined" class="undefined"></CustomTextBox>

如果值为 null 或未定义,我如何将属性设为可选

Stackbitz 解决方案

https://stackblitz.com/edit/angular-ivy-v1sybw

【问题讨论】:

  • 您看到我在帖子中使用新解决方案进行的编辑了吗?

标签: angular typescript angular9 property-binding


【解决方案1】:

试着在你的模板中写这个

<textarea [attr.id]="_id?_id:null" [attr.class]="_class?_class:null"></textarea>

这将检查您的_id_class 是否已设置,如果未设置,则返回值将是null,这将具有删除属性的效果,因此不会显示未定义的值。

【讨论】:

  • 谢谢亚历克西斯,我试过了,但仍然显示值未定义
  • 你能提供一个关于你的问题的stackblitz吗
  • Alexis ,除了“id”,一切看起来都不错,只有 id 显示值为 null
  • 这很奇怪,在 stackblitz 上这个改变可以完成工作:(如果你尝试 '' 而不是 null ?
【解决方案2】:

您可以像任何其他属性一样为 @Input 添加默认值:

@Input('id') _id:string = "defaultId";
@Input('class') _class:string = "defaultClass"

@input 的值为undefined 时,它将采用默认值。

如果您想在没有提供_id_class 的情况下完全隐藏CustomTextBox,您可以尝试:

showTextBox: boolean = false;

ngOnInit(): void {
    if(_id !== undefined && _class !== undefined){
         showTextBox= true;
    }
}

在您的 html 文件中:

<CustomTextBox *ngIf ="showTextBox"></CustomTextBox>

【讨论】:

  • 谢谢charbel,但是要添加默认值,我认为这不是一个好习惯,如果我使用ngIf,如果我没有传递任何值,控件将是不可见的
  • 您能详细说明一下吗?如果是 undefined 值,您希望 CustomTextBox 发生什么?
猜你喜欢
  • 1970-01-01
  • 2020-08-16
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
相关资源
最近更新 更多