Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
battmanz Avatar asked Sep 28 '16 18:09

battmanz


1 Answers

@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?
}
like image 97
Günter Zöchbauer Avatar answered Oct 18 '22 04:10

Günter Zöchbauer