如何检测Angular 2组件是否具有属性

时间:2016-09-28 18:04:14

标签: angular typescript

假设我有一个看起来像这样的Angular 2组件

@Component({
  selector: 'my-message',
  template: `
    <p *ngIf="messageWasSet">{{message}}</p>
    <p *ngIf="!messageWasSet">No message was specified</p>
  `
})
export class MessageComponent {
  @Input() public message: string;

  public messageWasSet: boolean; // How to calculate this?
}

以下是一些示例用法:

示例1

<my-message message="Hi world"></my-message>

<!-- Rendered innerHTML -->
<p>Hi world</p>

示例2

<!-- suppose obj.message = 'Viva Angular 2!' -->
<my-message [message]="obj.message"></my-message>

<!-- Rendered innerHTML -->
<p>Viva Angular 2!</p>

示例3

<!-- suppose obj.message = undefined -->
<my-message [message]="obj.message"></my-message>

<!-- Rendered innerHTML -->
<p></p>

示例4

<!-- Notice that there is no `message` binding at all -->
<my-message></my-message>

<!-- Rendered innerHTML -->
<p>No message was specified</p>

我的问题是如何在不使用messageWasSet 的情况下计算ElementRef布尔属性

2 个答案:

答案 0 :(得分:4)

@Component({
  selector: 'my-message',
  template: `
    <p *ngIf="messageWasSet">{{message}}</p>
    <p *ngIf="!messageWasSet">No message was specified</p>
  `
})
export class MessageComponent {
  private _message: string;      

  public get message() {
    return this._message;
  }

  @Input() public set message(value: string) {
    this.messageWasSet = true;
    this._message = value;
  }

  public messageWasSet: boolean; // How to calculate this?
}

答案 1 :(得分:0)

您可以创建messageWasSet作为属性,根据下面的message返回值,

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

@Component({
  selector: 'my-app',
  template: `<h3>How to detect if Angular 2 component has attribute</h3>
  <hr />
  Child component
  <my-message [message]="obj.message" ></my-message>
  `
})
export class AppComponent {
  obj = { message: 'hello' };
}

@Component({
  selector: 'my-message',
  template: `
    <p *ngIf="messageWasSet">{{message}}</p>
    <p *ngIf="!messageWasSet">No message was specified</p>
  `
})
export class MessageComponent {
  @Input() public message: string;

  get messageWasSet(){
    return !!this.message;
  }
}

这是Plunker!!

希望这会有所帮助!!