1

I want to set @HostBinding for specific conditions only. Suppose that I declared the @HostBinding like below in angular component

@Input() @HostBinding('innerHTML') mainvalue;

if the mainvalue is empty or undefined, then how can we stop working hostbinding?. currently if mainvalue is empty or undefined, then whole content of the component is going to deleted.

Thanks in advance.

wiki
  • 165
  • 1
  • 1
  • 6

2 Answers2

3

Use a setter on your input to conditionally set or keep your innerHTML host binding:

@Component({
  selector: 'app-test',
  template: '',
})
export class TestComponent {

  @Input() set mainValue (value: any) {
    if (value) {
      this.innerHTML = JSON.stringify(value, null, 2);
    }
    // otherwise keep the current innerHTML
  }

  @HostBinding('innerHTML') innerHTML;
}
hansmaad
  • 18,417
  • 9
  • 53
  • 94
0

ngIf directive to conditionally apply the host binding only when the mainvalue is defined and not empty. <ng-container *ngIf="mainvalue"> @Input() @HostBinding('innerHTML') mainvalue; enter code here

vishnu C
  • 19
  • 2