battmanz battmanz - 2 months ago 12
TypeScript Question

How to detect if Angular 2 component has attribute

Suppose I have an Angular 2 component that looks like this

@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?
}


Here are some example usages:

Example 1

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

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


Example 2

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

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


Example 3

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

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


Example 4

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

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


My question is how can I calculate the
messageWasSet
boolean property without using
ElementRef
?

Answer
@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?
}