Angular5:@Input属性,不需要值等于“true”?

时间:2018-01-23 17:12:13

标签: angular angular-components

我有这个组件:

export class TranslatedInputComponent implements OnInit {

  @Input() dto:DTO;
  @Input() multi:boolean;
}

“multi”必须是不需要参数的属性。如果需要多行输入,它的存在应该意味着“真实”并且如下所示使用:

<translated-input [dto]="newSymptom.title" multi></translated-input>

现在,我必须绑定一个值:

<translated-input [dto]="newSymptom.title" [multi]="true"></translated-input>

实现属性行为类似属性指令的最简洁方法是什么?

1 个答案:

答案 0 :(得分:0)

Material2写了以下方法:

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

将其用作:

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

HTML:

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

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

如果您使用Material2,则可以直接导入

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