角2分量输入无值 [英] Angular 2 component input without value

查看:91
本文介绍了角2分量输入无值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个组件,该组件的属性不需要任何值.例如,代替这样的东西:(我现在有)

I want to create a component that has attributes that need no value. For example, instead of something like this: (which I have now)

<app-document [mode]="'edit'" ... ></app-document>

<app-document [editMode]="true" ... ></app-document>

我宁愿拥有:

<app-document editMode ...></app-document>

因此,组件本身必须查看属性 editMode 是否存在.当我有很多这样的属性时,这看起来会干净很多.我还没有看到任何有关如何执行此操作的文档.可以吗?

So the component itself has to see whether the attribute editMode is present or not. This will look a lot cleaner when I have a lot of such attributes. I haven't seen any documentation on how to do this. Is it doable?

推荐答案

Material2 编写了以下方法:

/** Coerces a data-bound value (typically a string) to a boolean. */
export function coerceBooleanProperty(value: any): boolean {
  return value != null && `${value}` !== 'false';
}

在您的app-document组件中写类似的内容:

Write something like that in your app-document component:

private _editMode: boolean;
@Input()
get editMode() { return this._editMode; }
set editMode(value: any) { this._editMode = coerceBooleanProperty(value); }

然后:

editMode == true
<app-document editMode></app-document>

editMode == false
<app-document></app-document>

如果您使用Material2,则可以按如下所示简单地导入方法:

If you use Material2 you can simply import the method as follows:

import {coerceBooleanProperty} from '@angular/cdk/coercion';

这篇关于角2分量输入无值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆