布尔输入到角度2分量

met*_*eta 16 angular

我正在尝试编写一个可以在我的应用程序中重用的组件,有时会显示一个控制按钮,有时则不会.

理想情况下,我想从属性的存在或不存在得到这个,以便使用组件看起来像<generic-component hideControls></generic-component>,在我的组件中使用布尔变量,基于该属性是否存在,但我看不到这样做的方式.

有没有办法做到这一点?

我尝试过下面稍微杂乱的版本(虽然理想情况下我不需要在showControls/hideControls上设置一个值);

generic.component.html

<div>
  <div>Stuff</div>
  <div *ngIf="showControls">Controls</div>
</div>
Run Code Online (Sandbox Code Playgroud)

generic.component.ts

// imports etc.
@Component({
  selector: 'generic-selector',
  templateUrl: 'generic.component.html'
})
export class GenericComponent implements OnInit {
  @Input()
  public showControls: boolean = true;

  // other inputs and logic
}
Run Code Online (Sandbox Code Playgroud)

这失败了,因为用法<generic-selector showControls="false"></generic-selector>将showControls设置为字符串"false",这是真实的,而不是布尔值.因此,我必须通过在组件中添加大量混乱来获取输入并根据是否给出字符串"false"来转换为布尔值.一个非杂乱的方式来分类这将是值得赞赏的,但我更愿意能够做上面的其他选择.

Tie*_*han 20

这失败了,因为用法<generic-selector showControls="false"></generic-selector>将showControls设置为字符串"false",这是真实的,而不是布尔值.因此,我必须通过在组件中添加大量混乱来获取输入并根据是否给出字符串"false"来转换为布尔值.一个非杂乱的方式来分类这将是值得赞赏的,但我更愿意能够做上面的其他选择.

使用绑定

<generic-selector [showControls]="false"></generic-selector>
Run Code Online (Sandbox Code Playgroud)

  • [showControls] ="false"效果很好.showControls = {{false}}不起作用. (4认同)

Ram*_*ani 15

您可以Input像使用其他属性一样使用装饰器.唯一的技巧是当属性不存在时,值将是undefined,否则,该值将是空字符串.

逻辑:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: '',
  templateUrl: './boolean-component.component.html'
})
export class AppBooleanComponent implements OnInit {

  @Input('boolean-attribute') booleanAttr: boolean;

  ngOnInit() {
    this.booleanAttr = this.booleanAttr !== undefined;
    console.log(`Boolean attribute is ${this.booleanAttr ? '' : 'non-'}present!`);
  }

}
Run Code Online (Sandbox Code Playgroud)

模板1(记录'布尔属性存在!'):

<app-boolean-component boolean-attribute></app-boolean-component>
Run Code Online (Sandbox Code Playgroud)

模板2(记录'布尔属性不存在!'):

<app-boolean-component></app-boolean-component>
Run Code Online (Sandbox Code Playgroud)


hak*_*ogh 7

在Angular中,有两种方法可以为您的属性赋值:

  1. 使用HTML属性
  2. 方括号

在第一种情况下,即使您将分配一个可插入的字符串,您的属性值也将始终是一个字符串,就像每个HTML属性一样:{{true}}.

而在第二种情况下,它将被解释为JavaScript表达式,但在您的上下文中.因此,如果您有一个对象表示法,那么您的属性的值将被解析为一个对象.但是对于指定上下文,angular不使用"with"语句,因此您不能在那里使用全局变量,而只能使用插入组件范围的组件的属性.

<generic-selector [showControls]="false"></generic-selector>

在这种情况下,它将字符串"false"并将其转换为JavaScript.所以在JavaScript中,它是一个布尔值,然后你会得到它boolean.

但如果你有这样的东西: <generic-selector [showControls]="{myProp: 'val'}"></generic-selector>

那么showControls的类型将是object,其值将使myProp属性等于'val'.

但如果你有一些非文字,那么它将被视为你班级的财产:

<generic-selector [showControls]="location"></generic-selector>

那么如果你在包含你的组件范围内有一个location属性generic-selector那么它的location属性的值将被采用,否则它将是未定义的.

我建议你考虑使用ngOnInit来记录属性的类型和赋值.