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
?
@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?
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With