代码之家  ›  专栏  ›  技术社区  ›  Alan Choufa

无赋值的角度属性绑定

  •  0
  • Alan Choufa  · 技术社区  · 2 年前

    我想用 @Input() close = false 在父母身上 <my-reusable-component close></my-reusable-component> .

    像材质按钮一样 <button mat-button disabled></button> .

    但是我得到了“类型字符串不能分配给类型布尔…”。。

    知道吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Jcl    2 年前

    您需要通过将其绑定到布尔值来为其分配布尔值

    <my-reusable-component [close]="true"></my-reusable-component>
    

    否则,可以设置 @Input() 到可选类型(允许 undefined )检查一下有没有 未定义 要查看其定义和/或真实性:

    @Input() close: boolean | undefined;
    
    
    private isClosed() {
      return (this.close !== undefined && this.close !== false) || this.close === true;
    }
    

    然后你应该可以像这样使用它:

    <my-reusable-component close></my-reusable-component>
    

    或者:

    <我的可重用组件[close]=“true”></我的可重用组件>
    

    我在这里做了一个样本: https://stackblitz.com/edit/angular-lbn6d9?file=src/app/app.component.html

        2
  •  1
  •   Eliseo    2 年前

    您还可以使用@Attribute@Optional

    close:boolean
    constructor(@Optional() @Attribute('close') close:string){
       this.close=close!=null;
    }