Home > OS >  How to set @HostBinding for conditions in angular component
How to set @HostBinding for conditions in angular component

Time:01-23

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.

CodePudding user response:

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;
}

CodePudding user response:

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

  • Related