Search code examples
angularangular2-templateangular2-databinding

Angular component tag bind method


I am trying to set the width and height of a component alongside its initial declaration in a parent component's html. Having the following component tag (in the parent's html):

<app-ipe-artboard [artboard]="artboard" [ngStyle]="setStyle()"></app-ipe-artboard>

Where setStyle() is a method on the artboard component (itself):

@Component({
    selector: 'app-ipe-artboard'
})
export class ArtboardComponent implements OnInit {
    @Input() public artboard: Artboard;

    ngOnInit() {
    }

    setStyle(): object {
        return {
            width: this.artboard.width + 'px',
            height: this.artboard.height + 'px'
        };
    }
}

Is it possible to reach this method (not in the way I have put it now because it gives compile time error and undesired runtime behavior consecutively)? Or is the component not yet instantiated when it is rendered at this this place and does this need to be done somehow different?


Solution

  • The issue is that right now the parent component is looking for it's own setStyle method and not finding any, so it throws a runtime error. The methods on the app-ipe-artboard are scoped to that component and cannot be reached by the parent (unless you pass a reference to that component to your parent component, which doesn't do much to clean this up).

    Solution 1

    Assuming the behavior you are looking for is to set the width and height of the child component based on variables on the artboard, you can accomplish this with @HostBinding.

    @Component({
      selector: 'app-ipe-artboard'
    })
    export class ArtboardComponent implements OnInit {
        @Input() public artboard: Artboard;
        @HostBinding('style.width') artboardWidth;
        @HostBinding('style.height') artboardHeight;
    
        ngOnInit() {
          this.artboardWidth = artboard.width;
          this.artboardHeight = artboard.height;
        }
    }
    

    Solution 2

    Another way you can do this, since you have the artboard in the parent, is just move that setStyle method to the parent component.

    parent component

    @Component({
      template: `<app-ipe-artboard [artboard]="artboard" [ngStyle]="setStyle()"></app-ipe-artboard>`
    })
    export class ParentComponent {
      artboard: Artboard = {width: 500, height: 300};
    
      setStyle() {
        return { width: this.artboard.width + 'px', height: this.artboard.height + 'px' }
      }
    }
    

    Solution 3
    From Gunter's answer here.

    You need to pass the same value you would add to an element like and sanitize the styles.

    Sample code provided by Gunter:

    @HostBinding('style')
    get myStyle(): String {
      return this.sanitizer.bypassSecurityTrustStyle('background: red; display: block;');
    }
    
    constructor(private sanitizer:DomSanitizer) {}