【问题标题】:Angular component tag bind methodAngular 组件标签绑定方法
【发布时间】:2018-02-13 17:08:47
【问题描述】:

我正在尝试在父组件的 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'
        };
    }
}

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

【问题讨论】:

    标签: angular angular2-template angular2-databinding


    【解决方案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 的回答 here

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

    Gunter提供的示例代码:

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

    【讨论】:

    • 感谢您提供两种方法。我倾向于更喜欢第一个来保持组件本身的责任。这种方法是否还保持 artboardWidth 和 artboard.width 之间的活动数据绑定,如下所示:当用户调整组件大小时,它会反映在随附的业务对象中吗?那将是最有益的。
    • 实际上在实施时会出现此错误:[Angular] 无法绑定到“宽度”,因为它不是“app-ipe-artboard”的已知属性。 1. 如果 'app-ipe-artboard' 是一个 Angular 组件并且它有 'width' 输入,那么验证它是这个模块的一部分。 2. 如果“app-ipe-artboard”是一个 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@NgModule.schemas”以禁止显示此消息。 3. 允许任何属性添加“NO_ERRORS_SCHEMA”到这个组件的“@NgModule.schemas”。
    • 您是否在模块中声明了 AppIpeArtboardComponent(或该组件的任何类名)?
    • 你确定它是正确的模块吗?不幸的是,该错误与实际问题无关,我看不到相关代码。仔细检查您的模块声明并尝试进行故障排除。也许打开一个单独的问题?
    • 现在标记为答案...我选择的最终解决方案是基于此绑定到样式(通常):stackoverflow.com/a/46151691/468910
    猜你喜欢
    • 2020-03-19
    • 2020-11-17
    • 2018-08-02
    • 2018-11-15
    • 2018-03-26
    • 1970-01-01
    • 2017-05-24
    • 2017-05-16
    相关资源
    最近更新 更多