Search code examples
angularecmascript-6typescript2.2

How do you derive a component's size using @Self() decorator?


I'm working on a mechanism for calculating and setting CSS Grid layouts. Part of doing this requires my components being able to detect their own size in pixels. So far I've come across the @Self() decorator, but now that I'm actually at the point of using it I can't figure out how to derive any information from it about the component.

I made a class called GridFactory that I'm using to extend my component classes which is making it extra confusing trying to figure out how to add the super call properly in the constructor. So far my class looks like this.

export class GridFactory {
    ScreenCore   : ScrnCore = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener('window:resize', ['$event']) onResize(event){ this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){
        this.checkScrn();
    }

    checkScrn( specs: appSpecs ){
        this.ScreenCore.Width   = specs.width;
        this.ScreenCore.Height  = specs.height;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}

So far I'm only trying to call it on the app.component which I have set up like this

@Component({
  selector    : 'app',
  templateUrl : './app.component.html'
})

export class AppComponent extends GridFactory implements OnInit {
    MainFrame: SiteFrame;

    @HostListener('window:resize', ['$event']) onResize(event){ this.calcScreen(); }

    constructor(public appSpecs: ElementRef){
        super(appSpecs);
    }

    ngOnInit(){ this.calcScreen(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }
}

as of right now I'm getting this error in regards to the appScpecs variable

TS2304: Cannot find name 'appSpecs'.

I've been looking up everything I can think of to look up to find more info about this decorator but I just haven't found anything yet. Can anyone help me figure this out?

UPDATE

I changed the function to this

checkScrn(){
    this.ScreenCore.Width   = this.appSpecs.nativeElement.width;
    this.ScreenCore.Height  = this.appSpecs.nativeElement.height;

    this.activteGrid( this.ScreenCore );
    console.log(this.appSpecs.nativeElement.width);
}

I also decided to make one component class with everything in it just to put it all in one place until I figure out how to get it working. I'm not getting any errors but the results are turning up null on my screen and undefined in the console.


Solution

  • Try

    checkScrn(){
        this.ScreenCore.Width   = this.appSpecs.width;
        this.ScreenCore.Height  = this.appSpecs.height;
    
        this.activteGrid( this.ScreenCore );
    }
    

    appSpecs is a property, not a type, so using it as a parameter type is incorrect. You should be able to access this.appSpecs in any function of the class anyway.