Home > Software engineering >  Angular property binding without assignment
Angular property binding without assignment

Time:03-30

I want to create a reusable component with @Input() close = false and in the parent <my-reusable-component close></my-reusable-component>.

Like material button with <button mat-button disabled></button>.

But i got "type string is not assignable to type boolean..

Any idea ?

CodePudding user response:

You need to assign a boolean to it, by binding it to a boolean

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

Otherwise, you can set the @Input() to an optional type (allow undefined) and check for not undefined to see if it's defined and/or true:

@Input() close: boolean | undefined;


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

And then you should be able to use it either like:

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

or:

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

I've made a sample here: https://stackblitz.com/edit/angular-lbn6d9?file=src/app/app.component.html

CodePudding user response:

You can also use @Attribute @Optional

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