Conditional styling on host element

前端 未结 4 2293
既然无缘
既然无缘 2021-02-19 07:04

I have a component that all it does is render , its something like this:

@Component({
     selector: \'my-comp\',
     host: ???,
     template: `
         

        
4条回答
  •  忘掉有多难
    2021-02-19 07:14

    Not sure what you're trying to do but something like this should suffice where you use ngAfterViewInit and ElementRef:

    import {AfterViewInit, ElementRef} from '@angular/core';
    
    @Component({
       selector: 'my-comp',
       host: ???,
       template: `
         
       `
    })
    
     export default class MyComp implements AfterViewInit {
       @Input() title: string;
       public isChanged: boolean;
    
       constructor(private _ref: ElementRef) {}
    
       ngAfterViewInit() {
    
         var host = this._ref.nativeElement;
    
         if (this.isChanged) {
            host.style.width = '200px';
         }
       }
     }
    

    If you want to do some checking for isChanged every time it changes you could implement ngDoCheck instead/as well:

    ngDoCheck() {
    
      if (this.isChanged !== this.previousIsChanged) {
    
        var host = this._ref.nativeElement;
    
        if (this.isChanged) {
          host.style.width = '200px';
        }
      }
    }
    

提交回复
热议问题