0

我正在尝试在父组件的 html 中设置组件的宽度和高度以及其初始声明。具有以下组件标记(在父级的 html 中):

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

setStyle()画板组件(本身)上的方法在哪里:

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

是否有可能达到这种方法(不是我现在所说的方式,因为它会连续给出编译时错误和不希望的运行时行为)?或者当它在这个地方渲染时组件还没有被实例化,这需要以某种不同的方式完成吗?

4

1 回答 1

1

问题是现在父组件正在寻找它自己的setStyle方法并且没有找到任何方法,因此它会引发运行时错误。上的方法app-ipe-artboard仅限于该组件,父组件无法访问(除非您将该组件的引用传递给您的父组件,这对清理它没有多大作用)。

解决方案 1

假设您正在寻找的行为是根据 上的变量设置子组件的宽度和高度artboard,您可以使用 @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;
    }
}

解决方案 2

您可以这样做的另一种方法,因为您在父组件artboard中有,只需将该setStyle方法移动到父组件。

父组件

@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' }
  }
}

解决方案 3
来自 Gunter在此处的回答。

您需要传递您将添加到类似元素的相同值并清理样式。

Gunter提供的示例代码:

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

constructor(private sanitizer:DomSanitizer) {}
于 2018-02-13T17:23:03.700 回答