【问题标题】:Ionic Angular2 own ComponentIonic Angular2 自己的组件
【发布时间】:2017-12-24 18:17:01
【问题描述】:

我的组件html:

<div>
  {{text}}
  {{percentLeft}}
  {{innerColor}}
</div>

我的组件的 TS 文件

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

/**
 * Generated class for the TimeLeftBarComponent component.
 *
 * See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
 * for more info on Angular Components.
 */
@Component({
  selector: 'time-left-bar',
  templateUrl: 'time-left-bar.html'
})
export class TimeLeftBarComponent {
   @Input('text') text: string;
   @Input('percentLeft') percentLeft: number;
   @Input('innerColor') innerColor: string; 

   constructor() {}

}

我如何称呼这个组件:

<time-left-bar [percentLeft]="50" [text]="text" [innerColor]="black">
</time-left-bar>

它只显示我输入的第一个参数,

例如:

<time-left-bar [percentLeft]="50" [text]="text"  [innerColor]="black">
</time-left-bar>

仅输出50

<time-left-bar [text]="text"  [innerColor]="black" [percentLeft]="50">
</time-left-bar>

仅输出text

<time-left-bar  [innerColor]="black" [percentLeft]="50" [text]="text">
</time-left-bar>

仅输出 black

我做错了什么?

【问题讨论】:

  • 如果你这样改变会发生什么:首先声明一个带有数字值的属性:public aNumber = 50,然后在视图中&lt;time-left-bar [percentLeft]="aNumber" text="'text'" innerColor="'black'"&gt;?由于textinnerColor 只是字符串,因此您不需要属性绑定(请注意,我发送'text' 不是用单引号发送text)。
  • 它与单引号一起工作!
  • 如果答案解决了问题,能否将其标记为已接受的答案,以便我们关闭问题?谢谢:)

标签: angular typescript ionic2 ionic3


【解决方案1】:

如果您添加 [],那么 Angular 会将值计算为表达式。什么时候 您的组件的类上没有具有该名称的属性,或者它 没有值,则结果为 undefined 或 null。

因此,如果您只想为textinnerColor 发送字符串值,请使用单引号:

<time-left-bar ... [text]="'text'" [innerColor]="'black'"></time-left-bar>

更好的方法是为这些值创建属性并使用该名称(不带单引号):

public aNumber = 50;
public aText = 'some text';
public aColor = 'black';

在视图中:

<time-left-bar [text]="aText" [innerColor]="aColor" [percentLeft]="aNumber">
</time-left-bar>

【讨论】:

    猜你喜欢
    • 2016-12-22
    • 2017-07-16
    • 2017-12-08
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    相关资源
    最近更新 更多